-
Notifications
You must be signed in to change notification settings - Fork 5
/
requests.go
285 lines (235 loc) · 6.94 KB
/
requests.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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
package zhttp
import (
"context"
"crypto/tls"
"fmt"
"net"
"net/http"
"net/url"
"time"
"github.com/greyh4t/dnscache"
)
var ctxOptionKey = struct{}{}
func disableRedirect(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
}
// buildClient make a new client
func (z *Zhttp) buildClient(httpOptions *HTTPOptions, reqOptions *ReqOptions, cookieJar http.CookieJar) *http.Client {
client := &http.Client{
Transport: z.transport,
Jar: cookieJar,
Timeout: httpOptions.RequestTimeout,
}
if reqOptions.RequestTimeout > 0 {
client.Timeout = reqOptions.RequestTimeout
}
if reqOptions.DisableRedirect {
client.CheckRedirect = disableRedirect
}
return client
}
// createTransport create a global *http.Transport for all http client
func createTransport(options *HTTPOptions, cache *dnscache.Cache) *http.Transport {
transport := http.DefaultTransport.(*http.Transport).Clone()
transport.MaxIdleConnsPerHost = options.MaxIdleConnsPerHost
transport.MaxConnsPerHost = options.MaxConnsPerHost
transport.DisableKeepAlives = options.DisableKeepAlives
transport.DisableCompression = options.DisableCompression
if options.InsecureSkipVerify {
transport.TLSClientConfig = &tls.Config{InsecureSkipVerify: options.InsecureSkipVerify}
}
if options.IdleConnTimeout > 0 {
transport.IdleConnTimeout = options.IdleConnTimeout
}
if options.MaxIdleConns > 0 {
transport.MaxIdleConns = options.MaxIdleConns
}
if options.TLSHandshakeTimeout > 0 {
transport.TLSHandshakeTimeout = options.TLSHandshakeTimeout
}
transport.Proxy = func(req *http.Request) (*url.URL, error) {
reqOptions, ok := req.Context().Value(ctxOptionKey).(*ReqOptions)
if ok && len(reqOptions.Proxies) > 0 {
if p, ok := reqOptions.Proxies[req.URL.Scheme]; ok {
return p, nil
}
} else if len(options.Proxies) > 0 {
if p, ok := options.Proxies[req.URL.Scheme]; ok {
return p, nil
}
}
// get proxy from environment
return http.ProxyFromEnvironment(req)
}
dialer := &net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
}
if options.DialTimeout > 0 {
dialer.Timeout = options.DialTimeout
}
if options.KeepAlive != 0 {
dialer.KeepAlive = options.KeepAlive
}
transport.DialContext = makeDialContext(dialer, cache)
return transport
}
func makeDialContext(dialer *net.Dialer, cache *dnscache.Cache) func(ctx context.Context, network, addr string) (net.Conn, error) {
return func(ctx context.Context, network string, address string) (net.Conn, error) {
reqOptions, ok := ctx.Value(ctxOptionKey).(*ReqOptions)
if ok && reqOptions.HostIP != "" {
_, port, _ := net.SplitHostPort(address)
address = net.JoinHostPort(reqOptions.HostIP, port)
} else if cache != nil {
host, port, _ := net.SplitHostPort(address)
ip, err := cache.FetchOneV4String(host)
if err != nil {
return nil, err
}
address = net.JoinHostPort(ip, port)
}
return dialer.DialContext(ctx, network, address)
}
}
// doRequest send request with http client to server
func (z *Zhttp) doRequest(method, rawURL string, options *ReqOptions, jar http.CookieJar) (*Response, error) {
if options == nil {
options = &ReqOptions{}
}
rawURL, err := z.buildURL(rawURL, options)
if err != nil {
return nil, err
}
ctx, cancel := context.WithCancel(context.Background())
req, err := z.buildRequest(ctx, method, rawURL, options)
if err != nil {
cancel()
return nil, err
}
z.addCookies(req, options)
z.addHeaders(req, options)
client := z.buildClient(z.options, options, jar)
timeout := z.options.Timeout
if options.Timeout > 0 {
timeout = options.Timeout
}
resp, err := z.do(client, req, cancel, timeout)
if err != nil {
cancel()
return nil, err
}
return &Response{
RawResponse: resp,
StatusCode: resp.StatusCode,
Status: resp.Status,
ContentLength: resp.ContentLength,
Headers: Headers(resp.Header),
Body: &ZBody{
rawBody: &ReaderWithCancel{
rc: resp.Body,
cancel: cancel,
timeout: timeout,
},
},
}, nil
}
func (z *Zhttp) do(client *http.Client, req *http.Request, cancel context.CancelFunc,
timeout time.Duration) (*http.Response, error) {
if timeout > 0 {
timer := time.AfterFunc(timeout, cancel)
resp, err := client.Do(req)
timer.Stop()
if err == context.Canceled {
err = fmt.Errorf("%w (timeout exceeded while send request)", err)
}
return resp, err
}
return client.Do(req)
}
// buildRequest build request with body and other
func (z *Zhttp) buildRequest(ctx context.Context, method, rawURL string, options *ReqOptions) (*http.Request, error) {
if len(options.Proxies) > 0 || options.HostIP != "" {
ctx = context.WithValue(ctx, ctxOptionKey, options)
}
if options.Body == nil {
return http.NewRequestWithContext(ctx, method, rawURL, nil)
}
bodyReader, contentType, err := options.Body.Content()
if err != nil {
return nil, err
}
req, err := http.NewRequestWithContext(ctx, method, rawURL, bodyReader)
if err != nil {
return nil, err
}
if contentType != "" {
req.Header.Set("Content-Type", contentType)
}
return req, nil
}
// buildURL make url and set custom query
func (z *Zhttp) buildURL(rawURL string, options *ReqOptions) (string, error) {
if len(options.Query) > 0 {
parsedURL, err := url.Parse(rawURL)
if err != nil {
return "", err
}
if parsedURL.RawQuery != "" {
parsedURL.RawQuery += "&" + options.Query.Encode()
} else {
parsedURL.RawQuery = options.Query.Encode()
}
rawURL = parsedURL.String()
}
return rawURL, nil
}
// addHeaders handle custom headers
func (z *Zhttp) addHeaders(req *http.Request, options *ReqOptions) {
z.setDefaultHeaders(req, options)
// set global headers
z.setHeaders(req, z.options.Headers)
if z.options.UserAgent != "" {
req.Header.Set("User-Agent", z.options.UserAgent)
}
// set headers of each request
z.setHeaders(req, options.Headers)
if options.Host != "" {
req.Host = options.Host
}
if options.Auth.Username != "" {
req.SetBasicAuth(options.Auth.Username, options.Auth.Password)
}
if options.IsAjax {
req.Header.Set("X-Requested-With", "XMLHttpRequest")
}
if options.ContentType != "" {
req.Header.Set("Content-Type", options.ContentType)
}
if options.UserAgent != "" {
req.Header.Set("User-Agent", options.UserAgent)
}
}
func (z *Zhttp) setDefaultHeaders(req *http.Request, options *ReqOptions) {
if z.options.NoUA || options.NoUA {
// set empty string to prevent go client set default UA
req.Header.Set("User-Agent", "")
} else {
req.Header.Set("User-Agent", "Zhttp/2.0")
}
}
func (z *Zhttp) setHeaders(req *http.Request, headers map[string]string) {
for key, value := range headers {
req.Header[key] = []string{value}
}
}
// addCookies handle custom cookies
func (z *Zhttp) addCookies(req *http.Request, options *ReqOptions) {
for k, v := range z.options.Cookies {
if _, ok := options.Cookies[k]; !ok {
req.AddCookie(&http.Cookie{Name: k, Value: v})
}
}
for k, v := range options.Cookies {
req.AddCookie(&http.Cookie{Name: k, Value: v})
}
}