forked from go-resty/resty
-
Notifications
You must be signed in to change notification settings - Fork 0
/
util_curl.go
78 lines (68 loc) · 1.93 KB
/
util_curl.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
package resty
import (
"bytes"
"io"
"net/http"
"net/http/cookiejar"
"net/url"
"strings"
"github.com/go-resty/resty/v2/shellescape"
)
func buildCurlRequest(req *http.Request, httpCookiejar http.CookieJar) (curl string) {
// 1. Generate curl raw headers
curl = "curl -X " + req.Method + " "
// req.Host + req.URL.Path + "?" + req.URL.RawQuery + " " + req.Proto + " "
headers := dumpCurlHeaders(req)
for _, kv := range *headers {
curl += `-H ` + shellescape.Quote(kv[0]+": "+kv[1]) + ` `
}
// 2. Generate curl cookies
// TODO validate this block of code, I think its not required since cookie captured via Headers
if cookieJar, ok := httpCookiejar.(*cookiejar.Jar); ok {
cookies := cookieJar.Cookies(req.URL)
if len(cookies) > 0 {
curl += `-H ` + shellescape.Quote(dumpCurlCookies(cookies)) + " "
}
}
// 3. Generate curl body
if req.Body != nil {
buf, _ := io.ReadAll(req.Body)
req.Body = io.NopCloser(bytes.NewBuffer(buf)) // important!!
curl += `-d ` + shellescape.Quote(string(buf)) + " "
}
urlString := shellescape.Quote(req.URL.String())
if urlString == "''" {
urlString = "'http://unexecuted-request'"
}
curl += urlString
return curl
}
// dumpCurlCookies dumps cookies to curl format
func dumpCurlCookies(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(), "&")
}
// dumpCurlHeaders dumps headers to curl format
func dumpCurlHeaders(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)
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
}