-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathclient.go
111 lines (101 loc) · 2.49 KB
/
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
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
package xhttp
import (
"crypto/tls"
"net"
"net/http"
"time"
)
type Client struct {
HttpClient *http.Client
bodySize int // body size limit(MB), default is 10MB
}
func defaultClient() *Client {
return &Client{
HttpClient: &http.Client{
Timeout: 60 * time.Second,
Transport: &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: defaultTransportDialContext(&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
}),
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
MaxIdleConnsPerHost: 1000,
MaxConnsPerHost: 3000,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
DisableKeepAlives: true,
ForceAttemptHTTP2: true,
},
},
bodySize: 10, // default is 10MB
}
}
// NewClient , default tls.Config{InsecureSkipVerify: true}
func NewClient() (client *Client) {
return defaultClient()
}
func (c *Client) SetTransport(transport http.RoundTripper) (client *Client) {
c.HttpClient.Transport = transport
return c
}
func (c *Client) SetHttpTransport(transport *http.Transport) (client *Client) {
c.HttpClient.Transport = transport
return c
}
func (c *Client) SetHttpTLSConfig(tlsCfg *tls.Config) (client *Client) {
if ht, ok := c.HttpClient.Transport.(*http.Transport); ok {
ht.TLSClientConfig = tlsCfg
}
return c
}
func (c *Client) SetTimeout(timeout time.Duration) (client *Client) {
c.HttpClient.Timeout = timeout
return c
}
// set body size (MB), default is 10MB
func (c *Client) SetBodySize(sizeMB int) (client *Client) {
c.bodySize = sizeMB
return c
}
// typeStr is request type and response type
// default is TypeJSON
// first param is request type
// second param is response data type
func (c *Client) Req(typeStr ...string) *Request {
var (
reqTp = TypeJSON // default
resTp = ResTypeJSON // default
tLen = len(typeStr)
)
switch {
case tLen == 1:
tpp := typeStr[0]
if _, ok := _ReqContentTypeMap[tpp]; ok {
reqTp = tpp
}
case tLen > 1:
// first param is request type
tpp := typeStr[0]
if _, ok := _ReqContentTypeMap[tpp]; ok {
reqTp = tpp
}
// second param is response data type
stpp := typeStr[1]
if _, ok := _ResTypeMap[stpp]; ok {
resTp = stpp
}
}
if c == nil {
c = defaultClient()
}
r := &Request{
client: c,
Header: make(http.Header),
requestType: reqTp,
responseType: resTp,
}
r.Header.Set("Content-Type", _ReqContentTypeMap[reqTp])
return r
}