forked from tomnomnom/meg
-
Notifications
You must be signed in to change notification settings - Fork 3
/
gohttp.go
92 lines (78 loc) · 1.79 KB
/
gohttp.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
package main
import (
"bytes"
"crypto/tls"
"fmt"
"io/ioutil"
"net"
"net/http"
"strings"
"time"
)
var transport = &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
DisableKeepAlives: true,
DialContext: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: time.Second,
DualStack: true,
}).DialContext,
}
var httpClient = &http.Client{
Transport: transport,
}
func goRequest(r request) response {
httpClient.Timeout = r.timeout
if !r.followLocation {
httpClient.CheckRedirect = func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
}
}
var req *http.Request
var err error
if r.body != "" {
req, err = http.NewRequest(r.method, r.URL(), bytes.NewBuffer([]byte(r.body)))
} else {
req, err = http.NewRequest(r.method, r.URL(), nil)
}
if err != nil {
return response{request: r, err: err}
}
req.Close = true
if !r.HasHeader("Host") {
// add the host header to the request manually so it shows up in the output
r.headers = append(r.headers, fmt.Sprintf("Host: %s", r.Hostname()))
}
if !r.HasHeader("User-Agent") {
r.headers = append(r.headers, fmt.Sprintf("User-Agent: %s", userAgent))
}
for _, h := range r.headers {
parts := strings.SplitN(h, ":", 2)
if len(parts) != 2 {
continue
}
req.Header.Set(parts[0], parts[1])
}
resp, err := httpClient.Do(req)
if resp != nil {
defer resp.Body.Close()
}
if err != nil {
return response{request: r, err: err}
}
body, _ := ioutil.ReadAll(resp.Body)
// extract the response headers
hs := make([]string, 0)
for k, vs := range resp.Header {
for _, v := range vs {
hs = append(hs, fmt.Sprintf("%s: %s", k, v))
}
}
return response{
request: r,
status: resp.Status,
statusCode: resp.StatusCode,
headers: hs,
body: body,
}
}