http2curl Go Library

repository·master·Indexed 21 days ago

https://github.com/moul/http2curl

A 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.

Tokens
779
Snippets
5
Records
5
Agent score
24%

What's inside http2curl

  1. Convert a Go http.Request to a cURL command

    master

    Use 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=stu
  2. Convert an http.Request to a curl command using GetCurlCommand

    master

    Use 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:

    • If the request uses HTTPS, the -k flag is added.
    • The request body is read and escaped using bashEscape for the -d flag. The original req.Body is reset using ioutil.NopCloser so it can be read again by other processes.
    • Headers are sorted alphabetically and added via -H flags.
    • The --compressed flag is appended to the command.
    • The URL is automatically constructed if the scheme is missing.
    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())
    }
  3. Get the raw slice from CurlCommand

    master

    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()
  4. Use the CurlCommand type to get a string representation

    master

    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)