Skip to content

Commit

Permalink
更新response处理
Browse files Browse the repository at this point in the history
  • Loading branch information
lixizan committed Nov 26, 2022
1 parent 98471f6 commit 149f0d5
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 9 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ var afterFunc = func(ctx context.Context, resp *http.Response) (context.Context,
return ctx, err
}
var result = BaseResult{}
if err := jsoniter.Unmarshal(rc.Buffer.Bytes(), &result); err != nil {
if err := jsoniter.Unmarshal(rc.Bytes(), &result); err != nil {
return ctx, err
}
if result.Code == nil || *result.Code != 0 {
Expand Down
2 changes: 1 addition & 1 deletion internal/server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ var afterFunc = func(ctx context.Context, resp *http.Response) (context.Context,
return ctx, err
}
var result = BaseResult{}
if err := jsoniter.Unmarshal(rc.Buffer.Bytes(), &result); err != nil {
if err := jsoniter.Unmarshal(rc.Bytes(), &result); err != nil {
return ctx, err
}
if result.Code == nil || *result.Code != 0 {
Expand Down
21 changes: 14 additions & 7 deletions response.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import (
"net/http"

jsoniter "github.com/json-iterator/go"
"github.com/pkg/errors"
)

type Response struct {
Expand All @@ -28,19 +27,27 @@ func (c *Response) GetBody() ([]byte, error) {
return nil, c.err
}
if c.Response == nil || c.Body == nil {
return nil, errors.New("response is nil")
return []byte{}, nil
}
defer c.Body.Close()
return ioutil.ReadAll(c.Body)
if rc, ok := c.Body.(*ReadCloser); ok {
return rc.Bytes(), nil
}
b, err := ioutil.ReadAll(c.Body)
_ = c.Body.Close()
return b, err
}

func (c *Response) BindJSON(v interface{}) error {
if c.err != nil {
return c.err
}
if c.Response == nil || c.Body == nil {
return errors.New("response is nil")
return nil
}
if rc, ok := c.Body.(*ReadCloser); ok {
return jsoniter.Unmarshal(rc.Bytes(), v)
}
defer c.Body.Close()
return errors.WithStack(jsoniter.NewDecoder(c.Body).Decode(v))
err := jsoniter.NewDecoder(c.Body).Decode(v)
_ = c.Body.Close()
return err
}

0 comments on commit 149f0d5

Please sign in to comment.