archiveis/http.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
package archiveis import ( "fmt" "io" "net" "net/http" "strings" "time" ) func doRequest(method string, url string, body io.ReadCloser, timeout time.Duration) (*http.Response, []byte, error) { req, err := newRequest(method, url, body) if err != nil { return nil, nil, err } if method != "" && method != "get" { req.Header.Set("content-type", "application/x-www-form-urlencoded") } client := newClient(timeout) resp, err := client.Do(req) if err != nil { return resp, nil, fmt.Errorf("executing request: %s", err) } if resp.StatusCode/100 != 2 && resp.StatusCode/100 != 3 { return resp, nil, fmt.Errorf("%v request to %v received unhappy response status-code=%v", method, url, resp.StatusCode) } respBody, err := io.ReadAll(resp.Body) if err != nil { return resp, nil, fmt.Errorf("reading response body: %s", err) } if err := resp.Body.Close(); err != nil { return resp, respBody, fmt.Errorf("closing response body: %s", err) } return resp, respBody, nil } func newRequest(method string, url string, body io.ReadCloser) (*http.Request, error) { req, err := http.NewRequest(method, url, body) if err != nil { return nil, fmt.Errorf("creating %v request to %v: %s", method, url, err) } req.Host = HTTPHost hostname := strings.Split(BaseURL, "://")[1] req.Header.Set("Host", hostname) req.Header.Set("Origin", hostname) req.Header.Set("Authority", hostname) req.Header.Set("User-Agent", UserAgent) req.Header.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8") req.Header.Set("Referer", BaseURL+"/") return req, nil } func newClient(timeout time.Duration) *http.Client { c := &http.Client{ Timeout: timeout, Transport: &http.Transport{ Proxy: http.ProxyFromEnvironment, Dial: (&net.Dialer{ Timeout: timeout, KeepAlive: timeout, }).Dial, TLSHandshakeTimeout: timeout, ResponseHeaderTimeout: timeout, ExpectContinueTimeout: 1 * time.Second, }, } return c }