-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathoptions.go
116 lines (97 loc) · 2.38 KB
/
options.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
package gclient
import (
"context"
"github.com/jianzhiyao/gclient/consts"
"net/http"
"time"
)
type Option func(req *Client)
type CheckRedirectHandler func(req *http.Request, via []*http.Request) error
func OptTimeout(timeout time.Duration) Option {
return func(req *Client) {
req.clientTimeout = timeout
}
}
func OptContext(ctx context.Context) Option {
return func(req *Client) {
req.ctx = ctx
}
}
func OptHeader(key string, value ...string) Option {
return func(req *Client) {
req.headers[key] = value
}
}
func OptUserAgent(ua string) Option {
return OptHeader(consts.HeaderUserAgent, ua)
}
func OptHeaders(headers map[string][]string) Option {
return func(req *Client) {
for key, value := range headers {
req.headers[key] = value
}
}
}
func OptEnableGzip() Option {
return enableSign(SignGzip)
}
func OptDisableGzip() Option {
return disableSign(SignGzip)
}
func OptEnableBr() Option {
return enableSign(SignBr)
}
func OptDisableBr() Option {
return disableSign(SignBr)
}
func OptCookieJar(jar http.CookieJar) Option {
return func(req *Client) {
req.clientCookieJar = jar
}
}
func OptTransport(roundTripper http.RoundTripper) Option {
return func(req *Client) {
req.clientTransport = roundTripper
}
}
func OptCheckRedirectHandler(clientCheckRedirect CheckRedirectHandler) Option {
return func(req *Client) {
req.clientCheckRedirect = clientCheckRedirect
}
}
//OptRetry set retry num of requests in one client
func OptRetry(num int) Option {
return func(req *Client) {
req.retry = num
}
}
func enableSign(t Sign) Option {
return func(req *Client) {
req.sign |= int8(t)
var contentEncoding []string
if req.sign&int8(SignGzip) != 0 {
contentEncoding = append(contentEncoding, consts.ContentEncodingGzip)
}
if req.sign&int8(SignBr) != 0 {
contentEncoding = append(contentEncoding, consts.ContentEncodingBr)
}
if len(contentEncoding) > 0 {
req.headers[consts.HeaderAcceptEncoding] = contentEncoding
}
}
}
func disableSign(t Sign) Option {
return func(req *Client) {
req.sign ^= int8(t)
var contentEncoding []string
if req.sign&int8(SignGzip) != 0 {
contentEncoding = append(contentEncoding, consts.ContentEncodingGzip)
}
if req.sign&int8(SignBr) != 0 {
contentEncoding = append(contentEncoding, consts.ContentEncodingBr)
}
if len(contentEncoding) > 0 {
req.headers[consts.HeaderAcceptEncoding] = contentEncoding
}
}
}