-
Notifications
You must be signed in to change notification settings - Fork 190
/
Copy pathhttpreq.go
86 lines (69 loc) · 1.7 KB
/
httpreq.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
// Package httpreq provide an simple http requester and some useful util functions.
package httpreq
import (
"net/http"
"sync"
"time"
"github.com/gookit/goutil/netutil/httpctype"
)
// AfterSendFn callback func
type AfterSendFn func(resp *http.Response, err error)
// Doer interface for http client.
type Doer interface {
Do(req *http.Request) (*http.Response, error)
}
// DoerFunc implements the Doer
type DoerFunc func(req *http.Request) (*http.Response, error)
// Do send request and return response.
func (do DoerFunc) Do(req *http.Request) (*http.Response, error) {
return do(req)
}
// ReqLogger request logger interface
type ReqLogger interface {
Infof(format string, args ...any)
Errorf(format string, args ...any)
}
const defaultTimeout = 500 * time.Millisecond
var (
// global lock
_gl = sync.Mutex{}
// client cache map
cs = map[int]*Client{}
)
// NewClient create a new http client and cache it.
//
// Note: timeout unit is millisecond
func NewClient(timeout int) *Client {
_gl.Lock()
cli, ok := cs[timeout]
if !ok {
cli = NewWithTimeout(timeout)
cs[timeout] = cli
}
_gl.Unlock()
return cli
}
// MustResp check error and return response
func MustResp(r *http.Response, err error) *http.Response {
if err != nil {
panic(err)
}
return r
}
// MustRespX check error and create a new RespX instance
func MustRespX(r *http.Response, err error) *RespX {
if err != nil {
panic(err)
}
return NewResp(r)
}
// WithJSONType set request content type to JSON
func WithJSONType(opt *Option) {
opt.ContentType = httpctype.JSON
}
// WithData set request data, will auto convert to body data or query string
func WithData(data any) OptionFn {
return func(opt *Option) {
opt.Data = data
}
}