forked from asmcos/requests
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.go
82 lines (73 loc) · 1.92 KB
/
utils.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
package requests
import (
"bytes"
"io/ioutil"
"net/http"
"net/http/cookiejar"
"net/url"
"strings"
"github.com/ahuigo/requests/shellescape"
)
// BuildRequest -
func BuildRequest(method string, origurl string, args ...interface{}) (req *http.Request, err error) {
// call request Get
req, err = R().BuildRequest(method, origurl, args...)
return
}
func BuildCurlRequest(req *http.Request, args ...interface{}) (curl string) {
// 1. generate curl request
curl = "curl -X " + req.Method + " "
// req.Host + req.URL.Path + "?" + req.URL.RawQuery + " " + req.Proto + " "
headers := getHeaders(req)
for _, kv := range *headers {
curl += `-H ` + shellescape.Quote(kv[0]+": "+kv[1]) + ` `
}
// 1.2 generate curl with cookies
for _, arg := range args {
switch arg := arg.(type) {
case *cookiejar.Jar:
cookies := arg.Cookies(req.URL)
if len(cookies) > 0 {
curl += ` -H ` + shellescape.Quote(dumpCookies(cookies)) + " "
}
}
}
// body
if req.Body != nil {
buf, _ := ioutil.ReadAll(req.Body)
req.Body = ioutil.NopCloser(bytes.NewBuffer(buf)) // important!!
curl += `-d ` + shellescape.Quote(string(buf))
}
curl += " " + shellescape.Quote(req.URL.String())
return curl
}
func dumpCookies(cookies []*http.Cookie) string {
sb := strings.Builder{}
sb.WriteString("Cookie: ")
for _, cookie := range cookies {
sb.WriteString(cookie.Name + "=" + url.QueryEscape(cookie.Value) + "&")
}
return strings.TrimRight(sb.String(), "&")
}
// getHeaders
func getHeaders(req *http.Request) *[][2]string {
headers := [][2]string{}
for k, vs := range req.Header {
for _, v := range vs {
headers = append(headers, [2]string{k, v})
}
}
n := len(headers)
// fmt.Printf("%#v\n", headers)
// sort headers
for i := 0; i < n; i++ {
for j := n - 1; j > i; j-- {
jj := j - 1
h1, h2 := headers[j], headers[jj]
if h1[0] < h2[0] {
headers[jj], headers[j] = headers[j], headers[jj]
}
}
}
return &headers
}