-
Notifications
You must be signed in to change notification settings - Fork 4
/
http2curl.go
99 lines (79 loc) · 2.17 KB
/
http2curl.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
93
94
95
96
97
98
99
package http2curl
import (
"bytes"
"errors"
"fmt"
"io"
"net/http"
"sort"
"strings"
"unsafe"
)
// CurlCommand contains exec.Command compatible slice + helpers
type CurlCommand []string
// append appends a string to the CurlCommand
func (c *CurlCommand) append(newSlice ...string) {
*c = append(*c, newSlice...)
}
// String returns a ready to copy/paste command
func (c *CurlCommand) String() string {
return strings.Join(*c, " ")
}
func bashEscape(str string) string {
return `'` + strings.Replace(str, `'`, `'\''`, -1) + `'`
}
var ErrorURINull = errors.New("getCurlCommand: invalid request, req.URL is nil")
// b2s converts byte slice to a string without memory allocation.
// See https://groups.google.com/forum/#!msg/Golang-Nuts/ENgbUzYvCuU/90yGx7GUAgAJ .
//
// Note it may break if string and/or slice header will change
// in the future go versions.
func b2s(b []byte) string {
/* #nosec G103 */
return *(*string)(unsafe.Pointer(&b))
}
// GetCurlCommand returns a CurlCommand corresponding to an http.Request
func GetCurlCommand(req *http.Request) (*CurlCommand, error) {
if req.URL == nil {
return nil, ErrorURINull
}
command := CurlCommand{}
command.append("curl")
schema := req.URL.Scheme
requestURL := req.URL.String()
if schema == "" {
schema = "http"
if req.TLS != nil {
schema = "https"
}
requestURL = schema + "://" + req.Host + req.URL.Path
}
if schema == "https" {
command.append("-k")
}
command.append("-X", bashEscape(req.Method))
if req.Body != nil {
var buff bytes.Buffer
_, err := buff.ReadFrom(req.Body)
if err != nil {
return nil, fmt.Errorf("getCurlCommand: buffer read from body error: %w", err)
}
// reset body for potential re-reads
req.Body = io.NopCloser(bytes.NewBuffer(buff.Bytes()))
if len(buff.String()) > 0 {
bodyEscaped := bashEscape(buff.String())
command.append("-d", bodyEscaped)
}
}
var keys []string
for k := range req.Header {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
command.append("-H", bashEscape(fmt.Sprintf("%s: %s", k, strings.Join(req.Header[k], " "))))
}
command.append(bashEscape(requestURL))
command.append("--compressed")
return &command, nil
}