-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathhttp2curl_hertz.go
60 lines (43 loc) · 1.17 KB
/
http2curl_hertz.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
package http2curl
import (
"fmt"
"sort"
"strings"
"github.com/cloudwego/hertz/pkg/protocol"
)
// GetCurlCommandHertz returns a CurlCommand corresponding to an protocol.Request
func GetCurlCommandHertz(req *protocol.Request) (*CurlCommand, error) {
if req.URI() == nil {
return nil, ErrorURINull
}
command := CurlCommand{}
command.append("curl")
requestURL := req.URI().String()
if string(req.URI().Scheme()) == "https" {
command.append("-k")
}
command.append("-X", bashEscape(b2s(req.Method())))
body := req.Body()
if len(body) != 0 {
bodyEscaped := bashEscape(b2s(body))
command.append("-d", bodyEscaped)
}
headers := make(map[string][]string)
keys := make([]string, 0)
req.Header.VisitAll(func(key, value []byte) {
_, ok := headers[b2s(key)]
if !ok {
keys = append(keys, b2s(key))
headers[b2s(key)] = []string{b2s(value)}
} else {
headers[b2s(key)] = append(headers[b2s(key)], b2s(value))
}
})
sort.Strings(keys)
for _, key := range keys {
command.append("-H", bashEscape(fmt.Sprintf("%s: %s", key, strings.Join(headers[key], " "))))
}
command.append(bashEscape(requestURL))
command.append("--compressed")
return &command, nil
}