Skip to content

cURL Command Builder — Go source

Compose a copy-paste curl command from a form: method, headers, body, auth and flags — values POSIX-quoted safely. Paste an existing command to import it back. Runs locally with a shareable link.

This is the Go implementation — the same logic the interactive tool runs, in a shareable, citable form.

// Package curlbuilder is the Go twin of CosmoDev's src/lib/curl-builder.ts
// (dual source: the web lib is TypeScript, the CLI lib is Go — kept in
// lock-step). Pure + deterministic, never panics. The table-driven tests in
// curl-builder_test.go share vectors with src/lib/curl-builder.test.ts so the
// two implementations are held to the same contract.
//
// The builder composes a copy-paste curl command from structured input; the
// parser reads an existing command back into the structure (round-trip).
// Values are single-quoted with embedded quotes escaped — safe for POSIX
// shells. The flag order is fixed and deterministic (documented; the TS lib
// reproduces it): method (-X) → headers (-H, insertion order) → auth (-u) →
// data (-d) → then the boolean flags (-I -k -L --compressed) → the URL last.
package curlbuilder

import (
	"regexp"
	"strings"
)

// Header is one request header. Mirrors { key, value } in curl-builder.ts.
type Header struct {
	Key   string
	Value string
}

// Auth holds basic-auth credentials. Mirrors { user, password } in
// curl-builder.ts.
type Auth struct {
	User     string
	Password string
}

// CurlRequest mirrors the CurlRequest interface in curl-builder.ts. Method
// and Data are pointers so nil represents the TS undefined: a nil Method
// defaults to GET and a nil Data omits -d entirely (a non-nil empty Data is
// omitted too, matching the TS `data !== undefined && data !== ''` guard).
// ParseCurlCommand leaves Method nil when the command has no -X.
type CurlRequest struct {
	URL             string
	Method          *string // nil → GET (TS: undefined)
	Headers         []Header
	Data            *string // nil → no -d (TS: undefined)
	Auth            *Auth   // nil → no -u (TS: undefined)
	HeadOnly        bool
	Insecure        bool
	FollowRedirects bool
	Compressed      bool
}

// ParsedCurl mirrors the ParsedCurl interface in curl-builder.ts.
type ParsedCurl struct {
	Request CurlRequest
	// UnknownFlags lists flags the parser does not model, kept verbatim for
	// the round trip (TS: unknownFlags).
	UnknownFlags []string
}

// CurlBuildResult mirrors the CurlBuildResult union in curl-builder.ts:
// either { command, error: null } or { command: '', error }.
type CurlBuildResult struct {
	Command string
	Error   *string // nil on success (TS: error: null)
}

// CurlParseResult mirrors the CurlParseResult union in curl-builder.ts:
// either { parsed, error: null } or { parsed: null, error }.
type CurlParseResult struct {
	Parsed *ParsedCurl // nil on error (TS: parsed: null)
	Error  *string     // nil on success (TS: error: null)
}

// strptr returns a pointer to s. It builds the nullable fields of
// CurlRequest (Method, Data) in tests and callers.
func strptr(s string) *string { return &s }

// methods is the supported verb set, in the TS lib's join order for the
// error message (GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS).
var methods = []string{"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"}

var (
	// urlPrefixRe mirrors /^(https?:\/\/|\/|\$)/ — http(s)://, a root-relative
	// path or a shell variable reference.
	urlPrefixRe = regexp.MustCompile(`^(https?://|/|\$)`)
	// headerNameRe mirrors /^[A-Za-z0-9-]+$/ — header names are strict.
	headerNameRe = regexp.MustCompile(`^[A-Za-z0-9-]+$`)
)

// isSupportedMethod reports whether m is one of the supported verbs.
func isSupportedMethod(m string) bool {
	for _, v := range methods {
		if v == m {
			return true
		}
	}
	return false
}

// ShellQuote single-quotes a value and escapes embedded single quotes the
// POSIX way (' → '\'' — close, escaped quote, reopen). Go twin of
// shellQuote() in curl-builder.ts.
func ShellQuote(value string) string {
	return "'" + strings.ReplaceAll(value, "'", `'\''`) + "'"
}

// BuildCurlCommand builds the curl command. URL required; method/header
// names validated. Go twin of buildCurlCommand() in curl-builder.ts.
func BuildCurlCommand(req CurlRequest) CurlBuildResult {
	trimmedURL := strings.TrimSpace(req.URL)
	if trimmedURL == "" {
		return CurlBuildResult{Command: "", Error: strptr("A URL is required")}
	}
	if !urlPrefixRe.MatchString(trimmedURL) {
		return CurlBuildResult{Command: "", Error: strptr("URL must start with http://, https://, / or $ (a variable)")}
	}
	method := "GET"
	if req.Method != nil {
		method = strings.ToUpper(*req.Method)
	}
	if !isSupportedMethod(method) {
		raw := "GET"
		if req.Method != nil {
			raw = *req.Method // the TS message quotes the ORIGINAL, not uppercased
		}
		return CurlBuildResult{Command: "", Error: strptr("unsupported method " + raw + " (use " + strings.Join(methods, ", ") + ")")}
	}
	for _, h := range req.Headers {
		if !headerNameRe.MatchString(h.Key) {
			return CurlBuildResult{Command: "", Error: strptr("invalid header name \"" + h.Key + "\" (letters, digits and hyphens only)")}
		}
	}
	parts := []string{"curl"}
	if method != "GET" {
		parts = append(parts, "-X "+method)
	}
	for _, h := range req.Headers {
		parts = append(parts, "-H "+ShellQuote(h.Key+": "+h.Value))
	}
	if req.Auth != nil {
		parts = append(parts, "-u "+ShellQuote(req.Auth.User+":"+req.Auth.Password))
	}
	if req.Data != nil && *req.Data != "" {
		parts = append(parts, "-d "+ShellQuote(*req.Data))
	}
	if req.HeadOnly {
		parts = append(parts, "-I")
	}
	if req.Insecure {
		parts = append(parts, "-k")
	}
	if req.FollowRedirects {
		parts = append(parts, "-L")
	}
	if req.Compressed {
		parts = append(parts, "--compressed")
	}
	parts = append(parts, ShellQuote(trimmedURL))
	return CurlBuildResult{Command: strings.Join(parts, " "), Error: nil}
}

// splitWords shell word-splits a line respecting single and double quotes,
// mirroring splitWords() in curl-builder.ts. An opened-but-empty quote (e.g.
// '') still yields a word (the empty string).
func splitWords(line string) []string {
	var words []string
	var cur strings.Builder
	var quote byte // 0 → no active quote
	has := false
	for i := 0; i < len(line); i++ {
		ch := line[i]
		if quote != 0 {
			if ch == quote {
				quote = 0
			} else {
				cur.WriteByte(ch)
			}
		} else if ch == '\'' || ch == '"' {
			quote = ch
			has = true
		} else if ch == ' ' || ch == '\t' {
			if cur.Len() > 0 || has {
				words = append(words, cur.String())
			}
			cur.Reset()
			has = false
		} else {
			cur.WriteByte(ch)
			has = true
		}
	}
	if has {
		words = append(words, cur.String())
	}
	return words
}

// ParseCurlCommand parses a curl command line back into a request (best
// effort, ordered). Long-form flags (--request, --header, --user, --data,
// --head, --insecure, --location) are accepted; unmodelled flags are kept
// verbatim in UnknownFlags. Go twin of parseCurlCommand() in curl-builder.ts.
func ParseCurlCommand(line string) CurlParseResult {
	trimmed := strings.TrimSpace(line)
	if trimmed == "" {
		return CurlParseResult{Parsed: nil, Error: strptr("A command is required")}
	}
	// Line continuations: "\<newline>" joins the command into one line.
	words := splitWords(strings.ReplaceAll(trimmed, "\\\n", " "))
	if len(words) == 0 || words[0] != "curl" {
		return CurlParseResult{Parsed: nil, Error: strptr("command must start with curl")}
	}
	req := CurlRequest{}
	unknownFlags := []string{}
	i := 1
	for i < len(words) {
		w := words[i]
		switch {
		case w == "-X" || w == "--request":
			if i+1 < len(words) {
				req.Method = strptr(words[i+1])
			}
			i += 2
		case w == "-H" || w == "--header":
			if i+1 < len(words) {
				raw := words[i+1]
				if at := strings.Index(raw, ":"); at > 0 {
					req.Headers = append(req.Headers, Header{
						Key:   strings.TrimSpace(raw[:at]),
						Value: strings.TrimSpace(raw[at+1:]),
					})
				}
			}
			i += 2
		case w == "-u" || w == "--user":
			if i+1 < len(words) {
				raw := words[i+1]
				if at := strings.Index(raw, ":"); at == -1 {
					req.Auth = &Auth{User: raw, Password: ""}
				} else {
					req.Auth = &Auth{User: raw[:at], Password: raw[at+1:]}
				}
			}
			i += 2
		case w == "-d" || w == "--data":
			if i+1 < len(words) {
				req.Data = strptr(words[i+1])
			}
			i += 2
		case w == "-I" || w == "--head":
			req.HeadOnly = true
			i++
		case w == "-k" || w == "--insecure":
			req.Insecure = true
			i++
		case w == "-L" || w == "--location":
			req.FollowRedirects = true
			i++
		case w == "--compressed":
			req.Compressed = true
			i++
		case strings.HasPrefix(w, "-"):
			unknownFlags = append(unknownFlags, w)
			i++
		default:
			req.URL = w // last bare word wins
			i++
		}
	}
	if req.URL == "" {
		return CurlParseResult{Parsed: nil, Error: strptr("no URL found in command")}
	}
	return CurlParseResult{Parsed: &ParsedCurl{Request: req, UnknownFlags: unknownFlags}, Error: nil}
}

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →