-
Notifications
You must be signed in to change notification settings - Fork 7
/
config.go
117 lines (98 loc) · 2.59 KB
/
config.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
package hasaki
import (
"context"
"io"
"net/http"
"sync"
"time"
)
const (
defaultTimeout = 30 * time.Second
defaultMaxIdleConnsPerHost = 128
defaultMaxConnsPerHost = 128
)
type (
BeforeFunc func(ctx context.Context, request *http.Request) (context.Context, error)
AfterFunc func(ctx context.Context, response *http.Response) (context.Context, error)
)
var (
once_initer = sync.Once{}
defaultClient, _ = NewClient(WithHTTPClient(&http.Client{
Timeout: defaultTimeout,
Transport: &http.Transport{
MaxIdleConnsPerHost: defaultMaxIdleConnsPerHost,
MaxConnsPerHost: defaultMaxConnsPerHost,
},
}))
defaultBeforeFunc BeforeFunc = func(ctx context.Context, request *http.Request) (context.Context, error) {
return ctx, nil
}
defaultAfterFunc AfterFunc = func(ctx context.Context, response *http.Response) (context.Context, error) {
return ctx, nil
}
)
// SetClient 设置全局客户端
// Setting the global client
func SetClient(c *Client) {
once_initer.Do(func() { defaultClient = c })
}
type (
config struct {
BeforeFunc BeforeFunc // 请求前中间件
AfterFunc AfterFunc // 请求后中间件
HTTPClient *http.Client // HTTP客户端
ReuseBodyEnabled bool // 是否复用body
}
Option func(c *config)
)
// WithBefore 设置请求前中间件
// Setting up pre-request middleware
func WithBefore(fn BeforeFunc) Option {
return func(c *config) {
c.BeforeFunc = fn
}
}
// WithAfter 设置请求后中间件
// Setting up post-request middleware
func WithAfter(fn AfterFunc) Option {
return func(c *config) {
c.AfterFunc = fn
}
}
// WithHTTPClient 设置HTTP客户端
// Setting the HTTP client
func WithHTTPClient(client *http.Client) Option {
return func(c *config) {
c.HTTPClient = client
}
}
// WithReuseBody 开启Body可重复读; Response.Body可以被断言为BytesReadCloser, 调用Bytes()方法重复读取.
// Turn on Body repeatable read; Response.Body can be asserted as BytesReadCloser, call Bytes() method to repeat reads.
func WithReuseBody() Option {
return func(c *config) {
c.ReuseBodyEnabled = true
}
}
func withInitialize() Option {
return func(c *config) {
if c.BeforeFunc == nil {
c.BeforeFunc = defaultBeforeFunc
}
if c.AfterFunc == nil {
c.AfterFunc = defaultAfterFunc
}
if c.HTTPClient == nil {
c.HTTPClient = &http.Client{
Timeout: defaultTimeout,
Transport: &http.Transport{
MaxIdleConnsPerHost: defaultMaxIdleConnsPerHost,
MaxConnsPerHost: defaultMaxConnsPerHost,
},
}
}
}
}
type BytesReadCloser interface {
io.ReadCloser
Bytes() []byte
}