-
Notifications
You must be signed in to change notification settings - Fork 34
/
curl.go
68 lines (50 loc) · 1.46 KB
/
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
package hargo
import (
"bufio"
"encoding/json"
"net/url"
"strings"
"github.com/alessio/shellescape"
log "github.com/sirupsen/logrus"
)
// ToCurl converts a HAR Entry to a curl command line
// curl -X <method> -b "<name=value&name=value...>" -H <name: value> ... -d "<postData>" <url>
func ToCurl(r *bufio.Reader) (string, error) {
dec := json.NewDecoder(r)
var har Har
err := dec.Decode(&har)
if err != nil {
log.Error(err)
}
var command string
for _, entry := range har.Log.Entries {
cmd, err := fromEntry(entry)
if err != nil {
log.Error(err)
}
command += cmd + "\n\n"
}
return command, nil
}
func fromEntry(entry Entry) (string, error) {
// inspired by https://github.com/snoe/harToCurl/blob/master/harToCurl
command := "curl -X " + entry.Request.Method
if entry.Request.HTTPVersion == "HTTP/1.0" {
command += " -0"
}
var cookies []string
if len(entry.Request.Cookies) > 0 {
for _, cookie := range entry.Request.Cookies {
cookies = append(cookies, url.QueryEscape(cookie.Name)+"="+url.QueryEscape(cookie.Value))
}
command += " -b " + shellescape.Quote(strings.Join(cookies[:], "&")) + " "
}
for _, h := range entry.Request.Headers {
command += " -H " + shellescape.Quote(h.Name+": "+h.Value) + " "
}
if entry.Request.Method == "POST" && len(entry.Request.PostData.Text) > 0 {
command += "-d " + shellescape.Quote(entry.Request.PostData.Text)
}
command += " " + shellescape.Quote(entry.Request.URL)
return command, nil
}