Skip to content

Commit

Permalink
Update xhttp opt
Browse files Browse the repository at this point in the history
  • Loading branch information
onanying committed Jul 5, 2023
1 parent b16453c commit 90aef05
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 32 deletions.
36 changes: 36 additions & 0 deletions xhttp/options.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package xhttp

import (
"net/http"
"time"
)

var DefaultOptions = newDefaultOptions()

func newDefaultOptions() Options {
h := http.Header{}
h.Set("Content-Type", "application/json")
return Options{
Header: h,
Timeout: time.Second * 5,
}
}

type Options struct {
Header http.Header
Body Body

// 默认: time.Second * 5
Timeout time.Duration
}

func newOptions(opts []Options) Options {
current := DefaultOptions
for _, v := range opts {
current = v
}
if current.Timeout == 0 {
current.Timeout = DefaultOptions.Timeout
}
return current
}
33 changes: 1 addition & 32 deletions xhttp/request.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,39 +5,8 @@ import (
"net/http"
"net/url"
"strings"
"time"
)

var DefaultOptions = newDefaultOptions()

func newDefaultOptions() Options {
h := http.Header{}
h.Set("Content-Type", "application/json")
return Options{
Header: h,
Timeout: time.Second * 5,
}
}

type Options struct {
Header http.Header
Body string

// 默认: time.Second * 5
Timeout time.Duration
}

func newOptions(opts []Options) Options {
current := DefaultOptions
for _, v := range opts {
current = v
}
if current.Timeout == 0 {
current.Timeout = DefaultOptions.Timeout
}
return current
}

type Response struct {
*http.Response
Body Body
Expand Down Expand Up @@ -77,7 +46,7 @@ func Request(method string, u string, opts ...Options) (*Response, error) {
req := &http.Request{
Method: method,
URL: URL,
Body: io.NopCloser(strings.NewReader(opt.Body)),
Body: io.NopCloser(strings.NewReader(opt.Body.String())),
Header: opt.Header,
}
r, err := cli.Do(req)
Expand Down
13 changes: 13 additions & 0 deletions xhttp/request_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,19 @@ func TestRequest(t *testing.T) {
a.Nil(err)
}

func TestRequestPOST(t *testing.T) {
a := assert.New(t)

url := "https://github.com/"
opt := Options{
Body: Body("abc"),
}
resp, err := Request("POST", url, opt)

a.Equal(resp.StatusCode, 200)
a.Nil(err)
}

func TestRequestError(t *testing.T) {
a := assert.New(t)

Expand Down

0 comments on commit 90aef05

Please sign in to comment.