-
Notifications
You must be signed in to change notification settings - Fork 0
/
option.go
94 lines (81 loc) · 1.97 KB
/
option.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
package restgo
import (
"crypto/tls"
"crypto/x509"
"net/http"
"net/http/cookiejar"
"net/url"
"time"
)
type option struct {
baseURL *url.URL
globalHeader http.Header
transport http.RoundTripper
jar http.CookieJar
timeout time.Duration
checkRedirect func(req *http.Request, via []*http.Request) error
beforeHooks []BeforeHookFunc
afterHooks []AfterHookFunc
}
type OptionFn func(opt *option)
func WithBaseURL(baseURL string) OptionFn {
return func(opt *option) {
opt.baseURL, _ = url.ParseRequestURI(baseURL)
}
}
func WithGlobalHeader(header http.Header) OptionFn {
return func(opt *option) {
opt.globalHeader = header
}
}
func WithTransport(transport http.RoundTripper) OptionFn {
return func(opt *option) {
opt.transport = transport
}
}
func WithCert(certPool *x509.CertPool, cert tls.Certificate) OptionFn {
return func(opt *option) {
opt.transport = &http.Transport{
TLSClientConfig: &tls.Config{
RootCAs: certPool,
Certificates: []tls.Certificate{cert},
MinVersion: tls.VersionTLS12,
},
}
}
}
func WithJar(jar *cookiejar.Jar) OptionFn {
return func(opt *option) {
opt.jar = jar
}
}
func WithCookies(u *url.URL, cookies ...*http.Cookie) OptionFn {
return func(opt *option) {
if opt.jar == nil {
opt.jar, _ = cookiejar.New(nil)
}
opt.jar.SetCookies(u, cookies)
}
}
func WithTimeout(timeout time.Duration) OptionFn {
return func(opt *option) {
opt.timeout = timeout
}
}
func WithCheckRedirect(checkRedirect func(req *http.Request, via []*http.Request) error) OptionFn {
return func(opt *option) {
opt.checkRedirect = checkRedirect
}
}
// WithBeforeHook 挂载请求前的钩子函数
func WithBeforeHook(hook BeforeHookFunc) OptionFn {
return func(opt *option) {
opt.beforeHooks = append(opt.beforeHooks, hook)
}
}
// WithAfterHook 挂载请求后的钩子函数
func WithAfterHook(hook AfterHookFunc) OptionFn {
return func(opt *option) {
opt.afterHooks = append(opt.afterHooks, hook)
}
}