-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
88 lines (73 loc) · 1.81 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
package request
import (
"context"
"io"
"net/http"
"time"
)
type RoundTripper interface {
RoundTrip(context.Context, *Request) (*Response, error)
}
type Client struct {
PathParams map[string]string
AllowGetMethodPayload bool
httpClient *http.Client
}
func newClient() *Client {
t := &http.Transport{
DisableKeepAlives: false, //关闭连接复用,因为后台连接过多最后会造成端口耗尽
MaxIdleConns: -1, //最大空闲连接数量
IdleConnTimeout: time.Duration(3 * time.Second), //空闲连接超时时间
}
httpClient := &http.Client{
Transport: t,
Timeout: 2 * time.Minute,
}
return &Client{
httpClient: httpClient,
}
}
func (c *Client) roundTrip(ctx context.Context, r *Request) (resp *Response, err error) {
resp = &Response{Request: r}
host := r.getHeader("Host")
if host == "" {
host = r.URL.Host
}
if r.Timeout != 0 {
c.httpClient.Timeout = r.Timeout
}
var reqBody io.ReadCloser
if r.GetBody != nil {
reqBody, err = r.GetBody()
if err != nil {
return
}
}
req := &http.Request{
Method: r.Method,
Header: r.Headers.Clone(),
URL: r.URL,
Host: host,
Proto: "HTTP/1.1",
ProtoMajor: 1,
ProtoMinor: 1,
ContentLength: int64(len(r.Body)),
Body: reqBody,
GetBody: r.GetBody,
Close: r.close,
}
for _, cookie := range r.Cookies {
req.AddCookie(cookie)
}
if ctx != nil {
req = req.WithContext(ctx)
}
r.RawRequest = req
var httpResponse *http.Response
httpResponse, err = c.httpClient.Do(r.RawRequest)
resp.Response = httpResponse
return
}
func (c *Client) isPayloadForbid(m string) bool {
return (m == http.MethodGet && !c.AllowGetMethodPayload) || m == http.MethodHead || m == http.MethodOptions
}