Install http2curl
masterInstall the package using go get to add it to your Go project dependencies.
go get moul.io/http2curlrepository·master·Indexed 21 days ago
https://github.com/moul/http2curlA Go library that converts standard http.Request objects into curl command line strings. It provides the GetCurlCommand function to generate a CurlCommand type, which can be used as a string for debugging or as a slice of strings compatible with the os/exec package.
Install the package using go get to add it to your Go project dependencies.
go get moul.io/http2curlUse http2curl.GetCurlCommand to transform a standard Go http.Request object into a string representing a valid curl command line instruction. This is useful for debugging or reproducing HTTP requests manually.
import (
"http"
"moul.io/http2curl"
)
// ... setup request ...
command, _ := http2curl.GetCurlCommand(req)
fmt.Println(command)
// Output: curl -X PUT -d "{\"hello\":\"world\",\"answer\":42}" -H "Content-Type: application/json" http://www.example.com/abc/def.ghi?jlk=mno&pqr=stuUse GetCurlCommand(req *http.Request) to generate a *CurlCommand representing the provided HTTP request. The resulting command includes the HTTP method, headers, body (if present), and the target URL.
Key behaviors:
-k flag is added.bashEscape for the -d flag. The original req.Body is reset using ioutil.NopCloser so it can be read again by other processes.-H flags.--compressed flag is appended to the command.import (
"net/http"
"fmt"
"github.com/moul/http2curl"
)
func main() {
req, _ := http.NewRequest("POST", "https://example.com/api", strings.NewReader(`{"key":"value"}`))
req.Header.Set("Content-Type", "application/json")
curlCmd, err := http2curl.GetCurlCommand(req)
if err != nil {
panic(err)
}
fmt.Println(curlCmd.String())
}Since CurlCommand is defined as a []string, you can use it directly with Go's os/exec package to execute the command.
import "os/exec"
// curlCmd is a *http2curl.CurlCommand
cmd := exec.Command((*curlCmd)[0], (*curlCmd)[1:]...)
err := cmd.Run()The CurlCommand type is a slice of strings compatible with exec.Command. To obtain a single, ready-to-copy/paste command string, call the .String() method.
// Assuming curlCmd is a *http2curl.CurlCommand
commandString := curlCmd.String()
fmt.Println(commandString)