-
Notifications
You must be signed in to change notification settings - Fork 41
/
httpUtils.go
79 lines (62 loc) · 1.53 KB
/
httpUtils.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 main
import (
"crypto/tls"
"io/ioutil"
"net"
"net/http"
"time"
"github.com/EDDYCJY/fake-useragent"
)
func createClient() {
transport := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
DisableKeepAlives: true,
DialContext: (&net.Dialer{
Timeout: time.Duration(opts.Timeout) * time.Second,
KeepAlive: time.Second,
}).DialContext,
}
redirect := func(req *http.Request, via []*http.Request) error {
if opts.NoRedirects {
return http.ErrUseLastResponse
}
return nil
}
httpClient := &http.Client{
Transport: transport,
CheckRedirect: redirect,
Timeout: time.Duration(opts.Timeout+3) * time.Second,
}
config.httpClient = httpClient
}
func sendRequest(u string) (Response, error) {
response := Response{}
request, err := http.NewRequest("GET", u, nil)
if err != nil {
return response, err
}
request.Header.Add("User-Agent", browser.Random())
// Add headers passed in as arguments
for header, value := range config.Headers {
request.Header.Add(header, value)
}
// Add cookies passed in as arguments
request.Header.Add("Cookie", config.Cookies)
resp, err := config.httpClient.Do(request)
if err != nil {
return response, err
}
if resp.Body == nil {
return response, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return response, err
}
response.Body = string(body)
response.Headers = resp.Header
response.StatusCode = resp.StatusCode
response.ContentLength = int(resp.ContentLength)
return response, err
}