github.com/vyskocilm/postkid/builder@v0.0.0-20191001131220-20c88b283fad/curl.go (about) 1 package builder 2 3 import ( 4 "fmt" 5 "io" 6 "net/url" 7 "os/exec" 8 "strings" 9 ) 10 11 // Curl return curl command line 12 func (b *Builder) Curl(req *Request) error { 13 14 // curl 15 io.WriteString(b.w, b.curl) 16 // ... method 17 io.WriteString(b.w, " -X") 18 io.WriteString(b.w, req.Method) 19 20 // ... headers 21 for name, value := range req.Header { 22 io.WriteString(b.w, " -H '") 23 io.WriteString(b.w, name) 24 io.WriteString(b.w, ": ") 25 io.WriteString(b.w, value) 26 io.WriteString(b.w, "'") 27 } 28 29 if len(req.Body) > 0 && (req.Method == "POST" || req.Method == "PUT") { 30 io.WriteString(b.w, " --data '") 31 io.WriteString(b.w, strings.TrimSpace(req.Body)) //FIXME: escape ' 32 io.WriteString(b.w, "'") 33 } 34 35 // ... path 36 io.WriteString(b.w, " '") 37 io.WriteString(b.w, req.Host) 38 io.WriteString(b.w, "/") 39 io.WriteString(b.w, url.PathEscape(req.Path)) 40 41 // ... query 42 query := req.QueryString() 43 if query != "" { 44 io.WriteString(b.w, "?") 45 io.WriteString(b.w, query) 46 } 47 io.WriteString(b.w, "' ") 48 49 return nil 50 } 51 52 // Curl return exec.Command with arguments for curl 53 func (b *Builder) CurlCmd(req *Request) (*exec.Cmd, error) { 54 55 args := make([]string, 0) 56 57 // ... method 58 args = append(args, fmt.Sprintf("-X%s", req.Method)) 59 60 // ... headers 61 for name, value := range req.Header { 62 args = append(args, "-H") 63 args = append(args, fmt.Sprintf("%s: %s", name, value)) 64 } 65 66 if len(req.Body) > 0 && (req.Method == "POST" || req.Method == "PUT") { 67 args = append(args, "--data") 68 args = append(args, req.Body) 69 } 70 71 // ... path 72 path := fmt.Sprintf("%s/%s", req.Host, url.PathEscape(req.Path)) 73 74 // ... query 75 query := req.QueryString() 76 if query != "" { 77 path = fmt.Sprintf("%s?%s", path, query) 78 } 79 args = append(args, path) 80 81 return exec.Command(b.curl, args...), nil 82 }