Skip to content

cURL Command Builder — C# 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 C# implementation — the same logic the interactive tool runs, in a shareable, citable form.

// curl-builder — structured input → copy-paste curl command + reverse parser.
// C# port (canonical TS: src/lib/curl-builder.ts; Go twin: cli/curl-builder).
// Standard library only. Composes a copy-paste curl command from structured
// input; also parses 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: method (-X) → headers (-H, insertion order) → auth (-u) →
// data (-d) → boolean flags (-I -k -L --compressed) → the URL last. Absent
// optional fields are null; null data is treated like "" (omitted). Never
// throws — errors travel in the result's Error field (null on success).
using System;
using System.Collections.Generic;

public static class CurlBuilder
{
    public class Header
    {
        public string Key, Value;
        public Header(string key, string value) { Key = key; Value = value; }
    }

    public class Auth
    {
        public string User, Password;
        public Auth(string user, string password) { User = user; Password = password; }
    }

    public class CurlRequest
    {
        public string Url = "";
        public string Method;                                     // null = GET
        public List<Header> Headers = new List<Header>();         // insertion order kept
        public string Data;                                       // null or "" → omitted
        public Auth Auth;                                         // null = absent
        public bool HeadOnly, Insecure, FollowRedirects, Compressed;
    }

    public class BuildResult { public string Command = ""; public string Error; }

    public class ParsedCurl { public CurlRequest Request; public List<string> UnknownFlags = new List<string>(); }

    public class ParseResult { public ParsedCurl Parsed; public string Error; }

    static readonly string[] Methods = { "GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS" };

    /** POSIX single-quote a value: ' → '\'' (close, escaped quote, reopen). */
    public static string ShellQuote(string value) => "'" + value.Replace("'", "'\\''") + "'";

    static bool IsHeaderKey(string k)
    {
        if (string.IsNullOrEmpty(k)) return false;
        foreach (char c in k)
        {
            bool ok = (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '-';
            if (!ok) return false;
        }
        return true;
    }

    /** Build the curl command. URL required; method/header names validated. */
    public static BuildResult BuildCurlCommand(CurlRequest req)
    {
        var r = new BuildResult();
        string url = (req.Url ?? "").Trim();
        if (url.Length == 0) { r.Error = "A URL is required"; return r; }
        if (!(url.StartsWith("http://") || url.StartsWith("https://") || url.StartsWith("/") || url.StartsWith("$")))
        {
            r.Error = "URL must start with http://, https://, / or $ (a variable)";
            return r;
        }
        string method = (req.Method ?? "GET").ToUpperInvariant();
        if (Array.IndexOf(Methods, method) < 0)
        {
            r.Error = "unsupported method " + req.Method + " (use " + string.Join(", ", Methods) + ")";
            return r;
        }
        foreach (var h in req.Headers)
        {
            if (!IsHeaderKey(h.Key))
            {
                r.Error = "invalid header name \"" + h.Key + "\" (letters, digits and hyphens only)";
                return r;
            }
        }
        var parts = new List<string> { "curl" };
        if (method != "GET") parts.Add("-X " + method);
        foreach (var h in req.Headers) parts.Add("-H " + ShellQuote(h.Key + ": " + h.Value));
        if (req.Auth != null) parts.Add("-u " + ShellQuote(req.Auth.User + ":" + req.Auth.Password));
        if (!string.IsNullOrEmpty(req.Data)) parts.Add("-d " + ShellQuote(req.Data));
        if (req.HeadOnly) parts.Add("-I");
        if (req.Insecure) parts.Add("-k");
        if (req.FollowRedirects) parts.Add("-L");
        if (req.Compressed) parts.Add("--compressed");
        parts.Add(ShellQuote(url));
        r.Command = string.Join(" ", parts);
        return r;
    }

    /** Shell word-split respecting single and double quotes. */
    static List<string> SplitWords(string line)
    {
        var words = new List<string>();
        var cur = "";
        char? quote = null;
        var has = false;
        foreach (char ch in line)
        {
            if (quote.HasValue)
            {
                if (ch == quote.Value) quote = null;
                else cur += ch;
            }
            else if (ch == '\'' || ch == '"') { quote = ch; has = true; }
            else if (ch == ' ' || ch == '\t')
            {
                if (cur.Length > 0 || has) words.Add(cur);
                cur = "";
                has = false;
            }
            else { cur += ch; has = true; }
        }
        if (has) words.Add(cur); // any accumulated characters imply has
        return words;
    }

    /** Parse a curl command line back into a request (best effort, ordered). */
    public static ParseResult ParseCurlCommand(string line)
    {
        var r = new ParseResult();
        string trimmed = (line ?? "").Trim();
        if (trimmed.Length == 0) { r.Error = "A command is required"; return r; }
        var words = SplitWords(trimmed.Replace("\\\n", " "));
        if (words.Count == 0 || words[0] != "curl") { r.Error = "command must start with curl"; return r; }
        var req = new CurlRequest();
        var unknown = new List<string>();
        int n = words.Count;
        for (int i = 1; i < n; i++)
        {
            string w = words[i];
            string Next() => i + 1 < n ? words[++i] : null;
            if (w == "-X" || w == "--request") req.Method = Next();
            else if (w == "-H" || w == "--header")
            {
                string raw = Next();
                if (raw != null)
                {
                    int at = raw.IndexOf(':');
                    if (at > 0) req.Headers.Add(new Header(raw.Substring(0, at).Trim(), raw.Substring(at + 1).Trim()));
                }
            }
            else if (w == "-u" || w == "--user")
            {
                string raw = Next();
                if (raw != null)
                {
                    int at = raw.IndexOf(':');
                    req.Auth = at < 0 ? new Auth(raw, "") : new Auth(raw.Substring(0, at), raw.Substring(at + 1));
                }
            }
            else if (w == "-d" || w == "--data") req.Data = Next();
            else if (w == "-I" || w == "--head") req.HeadOnly = true;
            else if (w == "-k" || w == "--insecure") req.Insecure = true;
            else if (w == "-L" || w == "--location") req.FollowRedirects = true;
            else if (w == "--compressed") req.Compressed = true;
            else if (w.StartsWith("-")) unknown.Add(w);
            else req.Url = w;
        }
        if (req.Url.Length == 0) { r.Error = "no URL found in command"; return r; }
        r.Parsed = new ParsedCurl { Request = req, UnknownFlags = unknown };
        return r;
    }
}

// Example:
// CurlBuilder.ShellQuote("it's") → "'it'\\''s'"
// new CurlBuilder.CurlRequest { Url = "https://api.example.com", Method = "post",
//     Headers = { new CurlBuilder.Header("X-Tag", "it's") }, Data = "k=v" }
// CurlBuilder.BuildCurlCommand(req).Command
// → "curl -X POST -H 'X-Tag: it'\\''s' -d 'k=v' 'https://api.example.com'"
// CurlBuilder.ParseCurlCommand("curl -sL --compressed 'https://x.dev'").Parsed
// → Request { Url = "https://x.dev", Compressed = true }, UnknownFlags = ["-sL"]

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 →