-
Notifications
You must be signed in to change notification settings - Fork 0
/
http_client.go
79 lines (69 loc) · 1.57 KB
/
http_client.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
package do
import (
"context"
"crypto/tls"
"net"
"net/http"
"time"
)
type (
HTTPClientOption struct {
timeout time.Duration
skipVerify bool
transport *http.Transport
}
HTTPClientSetter func(*HTTPClientOption)
)
func HTTPClientWithTimeout(timeout time.Duration) HTTPClientSetter {
return func(ho *HTTPClientOption) {
ho.timeout = timeout
}
}
func HTTPClientSkipVerify() HTTPClientSetter {
return func(ho *HTTPClientOption) {
ho.skipVerify = true
}
}
func HTTPClientWithTransport(tp *http.Transport) HTTPClientSetter {
return func(ho *HTTPClientOption) {
ho.transport = tp
}
}
func NewHTTPClient(opts ...HTTPClientSetter) *http.Client {
opt := &HTTPClientOption{}
for _, set := range opts {
set(opt)
}
defaultTransportDialContext := func(dialer *net.Dialer) func(context.Context, string, string) (net.Conn, error) {
return dialer.DialContext
}
ts := http.DefaultTransport
if opt.transport != nil {
ts = opt.transport
} else if opt.skipVerify {
ts = &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: defaultTransportDialContext(&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
}),
ForceAttemptHTTP2: true,
MaxIdleConns: 100,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
TLSClientConfig: &tls.Config{
InsecureSkipVerify: true,
},
}
}
to := 10 * time.Second
if opt.timeout != 0 {
to = opt.timeout
}
client := &http.Client{
Timeout: to,
Transport: ts,
}
return client
}