Skip to content

Commit

Permalink
Merge pull request #9 from lxzan/dev
Browse files Browse the repository at this point in the history
debug mode
  • Loading branch information
lxzan authored Nov 8, 2023
2 parents 24c48fa + 96c62f8 commit 8588531
Show file tree
Hide file tree
Showing 5 changed files with 126 additions and 7 deletions.
35 changes: 30 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,18 +16,20 @@ http request library for golang
- [Features](#features)
- [Install](#install)
- [Usage](#usage)
- [Get](#get)
- [Post](#post)
- [Stream](#stream)
- [Error Stack](#error-stack)
- [Middleware](#middleware)
- [Get](#get)
- [Post](#post)
- [Stream](#stream)
- [Error Stack](#error-stack)
- [Middleware](#middleware)
- [Debug](#debug)

### Features

- [x] Buffer Pool
- [x] Trace the Error Stack
- [x] JSON / WWWForm Encoder
- [x] Request Before and After Middleware
- [x] Export CURL Command

### Install

Expand Down Expand Up @@ -160,3 +162,26 @@ var url = "https://api.github.com/search/repositories"
cli, _ := hasaki.NewClient(before, after)
cli.Get(url).Send(nil)
```

#### Debug

```go
hasaki.
Post("http://127.0.0.1:3000").
Debug().
SetHeader("x-username", "123").
SetHeader("user-agent", "hasaki").
SetEncoder(hasaki.FormEncoder).
Send(url.Values{
"name": []string{"洪荒"},
"age": []string{"456"},
})
```

```bash
curl -X POST 'http://127.0.0.1:3000' \
--header 'User-Agent: hasaki' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--header 'X-Username: 123' \
--data-raw 'age=456&name=%E6%B4%AA%E8%8D%92'
```
34 changes: 32 additions & 2 deletions client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package hasaki
import (
"context"
"fmt"
"net"
"net/http"
"net/url"
"strconv"
Expand Down Expand Up @@ -195,7 +196,7 @@ func TestRequest_Send(t *testing.T) {
resp := Post("http://%s", addr).
SetEncoder(FormEncoder).
Send(nil)
assert.Error(t, resp.Err())
assert.NoError(t, resp.Err())
})

t.Run("", func(t *testing.T) {
Expand Down Expand Up @@ -292,6 +293,8 @@ func TestResponse(t *testing.T) {
case "/test":
writer.WriteHeader(http.StatusOK)
writer.Write([]byte(`{"name":"caster"}`))
case "/204":
writer.WriteHeader(http.StatusNoContent)
default:
writer.WriteHeader(http.StatusOK)
}
Expand Down Expand Up @@ -336,10 +339,37 @@ func TestResponse(t *testing.T) {
})

t.Run("bind json error 2", func(t *testing.T) {
resp := Post("http://%s/test", addr).Send(nil)
resp := Post("http://%s/test", addr).Send(map[string]any{
"name": "xxx",
})
resp.Body = nil
inputs := struct{ Name string }{}
err := resp.BindJSON(&inputs)
assert.Error(t, err)
})

t.Run("204 response", func(t *testing.T) {
resp1 := Post("http://%s/204", addr).
Debug().
SetEncoder(JsonEncoder).
Send(map[string]any{
"name": "xxx",
})
assert.NotNil(t, resp1.Body)

resp2 := Post("http://%s/204", addr).
Debug().
SetEncoder(FormEncoder).
Send(nil)
assert.NotNil(t, resp2.Body)
})

t.Run("post form error", func(t *testing.T) {
var netConn *net.TCPConn
resp := Post("http://%s/204", addr).
Debug().
SetEncoder(FormEncoder).
Send(net.Conn(netConn))
assert.Error(t, resp.Err())
})
}
6 changes: 6 additions & 0 deletions codec.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,9 @@ var (
type json_encoder struct{}

func (j json_encoder) Encode(v any) (io.Reader, error) {
if v == nil {
return nil, nil
}
w := bytebufferpool.Get()
err := jsoniter.ConfigFastest.NewEncoder(w).Encode(v)
r := &closerWrapper{B: w, R: bytes.NewReader(w.B)}
Expand All @@ -53,6 +56,9 @@ type form_encoder struct{}

// Encode do not support float number
func (f form_encoder) Encode(v any) (io.Reader, error) {
if v == nil {
return nil, nil
}
if values, ok := v.(url.Values); ok {
return strings.NewReader(values.Encode()), nil
}
Expand Down
8 changes: 8 additions & 0 deletions codec_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package hasaki

import (
"bytes"
"net"
"net/url"
"testing"

Expand All @@ -18,6 +19,13 @@ func TestForm_encoder_Encode(t *testing.T) {
"name": []string{"caster"},
})
assert.NoError(t, err2)

_, err3 := FormEncoder.Encode(nil)
assert.NoError(t, err3)

var netConn *net.TCPConn
_, err4 := FormEncoder.Encode(net.Conn(netConn))
assert.Error(t, err4)
}

func TestStreamEncoder(t *testing.T) {
Expand Down
50 changes: 50 additions & 0 deletions request.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
package hasaki

import (
"bytes"
"context"
"fmt"
"io"
"net/http"
neturl "net/url"
"strings"

"github.com/go-playground/form/v4"
"github.com/pkg/errors"
Expand All @@ -24,6 +28,7 @@ type Request struct {
encoder Encoder
before BeforeFunc
after AfterFunc
debug bool
}

// NewRequest 新建一个请求
Expand All @@ -48,6 +53,13 @@ func Delete(url string, args ...any) *Request {
return defaultClient.Delete(url, args...)
}

// Debug 开启调试模式, 打印CURL命令
// Enable debug mode, print CURL commands
func (c *Request) Debug() *Request {
c.debug = true
return c
}

// SetBefore 设置请求前中间件
// Setting up pre-request middleware
func (c *Request) SetBefore(f BeforeFunc) *Request {
Expand Down Expand Up @@ -150,6 +162,9 @@ func (c *Request) Send(body any) *Response {
return response
}

// 打印CURL命令
c.printCURL(req)

// 发起请求
resp, err2 := c.client.Do(req)
if err2 != nil {
Expand All @@ -166,3 +181,38 @@ func (c *Request) Send(body any) *Response {
response.Response = resp
return response
}

func (c *Request) printCURL(req *http.Request) {
if !c.debug {
return
}

var body = bytes.NewBufferString("")
if req.Body != nil {
_, _ = io.Copy(body, req.Body)
}

var builder = strings.Builder{}
var line = fmt.Sprintf("curl -X %s '%s' \\\n", req.Method, req.URL.String())
builder.WriteString(line)
for k, arr := range req.Header {
for _, v := range arr {
line = fmt.Sprintf(" --header '%s: %s'", k, v)
builder.WriteString(line)
if req.Body != nil {
builder.WriteString(" \\\n")
} else {
builder.WriteString(" \n")
}
}
}

builder.WriteString(" --data-raw ")
builder.WriteString("'")
if body.Len() < 128*1024 {
builder.WriteString(strings.TrimSuffix(body.String(), "\n"))
}
builder.WriteString("'")
println(builder.String())
req.Body = io.NopCloser(body)
}

0 comments on commit 8588531

Please sign in to comment.