Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

httpx:增加error判断 #264

Merged
merged 3 commits into from
Nov 12, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ github.com/rogpeppe/go-internal v1.11.0 h1:cWPaGQEPrBb5/AsnsZesgZZ9yb1OQ+GOISoDN
github.com/rogpeppe/go-internal v1.11.0/go.mod h1:ddIwULY96R17DhadqLgMfk9H9tvdUzkipdSkR5nkCZA=
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
golang.org/x/exp v0.0.0-20231006140011-7918f672742d h1:jtJma62tbqLibJ5sFQz8bKtEM8rJBtfilJ2qTU199MI=
golang.org/x/exp v0.0.0-20231006140011-7918f672742d/go.mod h1:ldy0pHrwJyGW56pPQzzkH36rKxoZW1tw7ZJpeKx+hdo=
golang.org/x/sync v0.4.0 h1:zxkM55ReGkDlKSM+Fu41A+zmbZuaPVbGMzvvdUPznYQ=
Expand Down
9 changes: 9 additions & 0 deletions net/httpx/request.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,9 @@ func NewRequest(ctx context.Context, method, url string) *Request {

// JSONBody 使用 JSON body
func (req *Request) JSONBody(val any) *Request {
if req.err != nil {
return req
}
req.req.Body = io.NopCloser(iox.NewJSONReader(val))
req.req.Header.Set("Content-Type", "application/json")
return req
Expand All @@ -50,13 +53,19 @@ func (req *Request) Client(cli *http.Client) *Request {
}

func (req *Request) AddHeader(key string, value string) *Request {
if req.err != nil {
return req
}
req.req.Header.Add(key, value)
return req
}

// AddParam 添加查询参数
// 这个方法性能不好,但是好用
func (req *Request) AddParam(key string, value string) *Request {
if req.err != nil {
return req
}
q := req.req.URL.Query()
q.Add(key, value)
req.req.URL.RawQuery = q.Encode()
Expand Down
6 changes: 6 additions & 0 deletions net/httpx/request_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -116,3 +116,9 @@ func TestRequestAddHeader(t *testing.T) {
type User struct {
Name string
}

func TestNewRequest_ReturnError(t *testing.T) {
flycash marked this conversation as resolved.
Show resolved Hide resolved
req := NewRequest(context.Background(), http.MethodGet, "://localhost:80/a")
assert.NotNil(t, req.err)
assert.Nil(t, req.req)
}
Loading