-
Notifications
You must be signed in to change notification settings - Fork 43
Expand file tree
/
Copy pathcurl.go
More file actions
46 lines (36 loc) · 941 Bytes
/
curl.go
File metadata and controls
46 lines (36 loc) · 941 Bytes
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
package httplog
import (
"fmt"
"net/http"
"strings"
)
// CURL returns a curl command for the given request and body.
func CURL(req *http.Request, reqBody string) string {
var b strings.Builder
fmt.Fprintf(&b, "curl")
if req.Method != "GET" && req.Method != "POST" {
fmt.Fprintf(&b, " -X %s", req.Method)
}
fmt.Fprintf(&b, " %s", singleQuoted(requestURL(req)))
if req.Method == "POST" {
fmt.Fprintf(&b, " --data-raw %s", singleQuoted(reqBody))
}
for name, vals := range req.Header {
for _, val := range vals {
fmt.Fprintf(&b, " -H %s", singleQuoted(fmt.Sprintf("%s: %s", name, val)))
}
}
return b.String()
}
func singleQuoted(v string) string {
return fmt.Sprintf("'%s'", strings.ReplaceAll(v, "'", `'\''`))
}
func scheme(r *http.Request) string {
if r.TLS != nil {
return "https"
}
return "http"
}
func requestURL(r *http.Request) string {
return fmt.Sprintf("%s://%s%s", scheme(r), r.Host, r.URL)
}