cobracurl is a Go package that helps you build HTTP requests from Cobra CLI commands — perfect for developers converting curl
commands into reproducible CLI tools.
If you're building a CLI app with Cobra and want to recreate or debug HTTP requests using cURL-like arguments, cobracurl
provides an easy way to translate CLI flags into a fully-formed *http.Request
.
- Define CLI flags for common HTTP request elements (method, URL, headers, body, etc.)
- Generate
*http.Request
objects from those flags - Minimal, dependency-free, and composable
- Easy integration with existing Cobra commands
go get github.com/cerberauth/cobracurl
- Register flags on your Cobra command
import "github.com/cerberauth/cobracurl"
func init() {
cobracurl.RegisterFlags(rootCmd.Flags())
}
- Build the HTTP request in your command's Run function
cmd := &cobra.Command{
Use: "send",
RunE: func(cmd *cobra.Command, args []string) error {
req, err := cobracurl.BuildRequest(cmd, args)
if err != nil {
return err
}
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
fmt.Println("Response:", string(body))
return nil
},
}
- Example CLI command
yourcli send \
--method POST \
--url https://api.example.com/data \
--header "Content-Type: application/json" \
--data '{"foo":"bar"}'
func RegisterFlags(flags *pflag.FlagSet)
Register the flags for HTTP method, URL, headers, and body. This function should be called in the init()
function of your Cobra command.
func BuildRequest(cmd *cobra.Command, args []string) (*http.Request, error)
Builds an *http.Request
object based on the flags set in the Cobra command. It returns an error if any required flags are missing or if the request cannot be created.
See example/ for a minimal CLI tool using cobracurl.
This repository is licensed under the MIT License @ CerberAuth. You are free to use, modify, and distribute the contents of this repository for educational and testing purposes.