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).
// C++17, 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 POSIX single-quoted (' → '\'') — safe for POSIX
// shells. Fixed flag order: method (-X) → headers (-H, insertion order) →
// auth (-u) → data (-d) → booleans (-I -k -L --compressed) → the URL last.
// Never throws on malformed input — errors travel in result.error (nullopt
// on success).
#include <cctype>
#include <optional>
#include <string>
#include <vector>

namespace curlbuilder {

struct Header { std::string key, value; };
struct Auth { std::string user, password; };

struct CurlRequest {
    std::string url;
    std::optional<std::string> method;   // nullopt = GET
    std::vector<Header> headers;         // insertion order kept
    std::optional<std::string> data;     // nullopt or "" → omitted
    std::optional<Auth> auth;            // nullopt = absent
    bool headOnly = false, insecure = false, followRedirects = false, compressed = false;
};

struct CurlBuildResult { std::string command; std::optional<std::string> error; };
struct ParsedCurl { CurlRequest request; std::vector<std::string> unknownFlags; };
struct CurlParseResult { std::optional<ParsedCurl> parsed; std::optional<std::string> error; };

inline std::string trim(const std::string &s) {
    const char *ws = " \t\n\r\f\v";
    size_t b = s.find_first_not_of(ws);
    if (b == std::string::npos) return "";
    size_t e = s.find_last_not_of(ws);
    return s.substr(b, e - b + 1);
}

inline bool isMethod(const std::string &m) {
    static const char *const kMethods[] = {"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"};
    for (const char *x : kMethods)
        if (m == x) return true;
    return false;
}

inline bool isHeaderKey(const std::string &k) {
    if (k.empty()) return false;
    for (unsigned char c : k) {
        bool ok = (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '-';
        if (!ok) return false;
    }
    return true;
}

// POSIX single-quote a value: ' → '\'' (close, escaped quote, reopen).
inline std::string shellQuote(const std::string &value) {
    std::string out = "'";
    for (char c : value) {
        if (c == '\'') out += "'\\''";
        else out += c;
    }
    return out + "'";
}

// Build the curl command. URL required; method/header names validated.
inline CurlBuildResult buildCurlCommand(const CurlRequest &req) {
    const std::string url = trim(req.url);
    if (url.empty()) return {"", std::string("A URL is required")};
    const bool okScheme = url.rfind("https://", 0) == 0 || url.rfind("http://", 0) == 0 ||
                          url[0] == '/' || url[0] == '$';
    if (!okScheme) return {"", std::string("URL must start with http://, https://, / or $ (a variable)")};
    const std::string rawMethod = req.method.value_or("GET");
    std::string method = rawMethod;
    for (char &c : method) c = (char)std::toupper((unsigned char)c);
    if (!isMethod(method))
        return {"", "unsupported method " + rawMethod + " (use GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS)"};
    for (const Header &h : req.headers)
        if (!isHeaderKey(h.key))
            return {"", "invalid header name \"" + h.key + "\" (letters, digits and hyphens only)"};
    std::vector<std::string> parts{"curl"};
    if (method != "GET") parts.push_back("-X " + method);
    for (const Header &h : req.headers) parts.push_back("-H " + shellQuote(h.key + ": " + h.value));
    if (req.auth) parts.push_back("-u " + shellQuote(req.auth->user + ":" + req.auth->password));
    if (req.data && !req.data->empty()) parts.push_back("-d " + shellQuote(*req.data));
    if (req.headOnly) parts.push_back("-I");
    if (req.insecure) parts.push_back("-k");
    if (req.followRedirects) parts.push_back("-L");
    if (req.compressed) parts.push_back("--compressed");
    parts.push_back(shellQuote(url));
    std::string cmd;
    for (size_t i = 0; i < parts.size(); i++) {
        if (i) cmd += ' ';
        cmd += parts[i];
    }
    return {cmd, std::nullopt};
}

// Shell word-split respecting single and double quotes.
inline std::vector<std::string> splitWords(const std::string &line) {
    std::vector<std::string> words;
    std::string cur;
    char quote = 0;
    bool has = false;
    for (char ch : line) {
        if (quote) {
            if (ch == quote) quote = 0;
            else cur += ch;
        } else if (ch == '\'' || ch == '"') {
            quote = ch;
            has = true;
        } else if (ch == ' ' || ch == '\t') {
            if (!cur.empty() || has) words.push_back(cur);
            cur.clear();
            has = false;
        } else {
            cur += ch;
            has = true;
        }
    }
    if (has) words.push_back(cur); // any accumulated characters imply has
    return words;
}

// Parse a curl command line back into a request (best effort, ordered).
inline CurlParseResult parseCurlCommand(const std::string &line) {
    const std::string trimmed = trim(line);
    if (trimmed.empty()) return {std::nullopt, std::string("A command is required")};
    std::string joined;
    for (size_t i = 0; i < trimmed.size(); i++) { // TS: replace(/\\\n/g, ' ')
        if (trimmed[i] == '\\' && i + 1 < trimmed.size() && trimmed[i + 1] == '\n') { joined += ' '; i++; }
        else joined += trimmed[i];
    }
    const std::vector<std::string> words = splitWords(joined);
    if (words.empty() || words[0] != "curl")
        return {std::nullopt, std::string("command must start with curl")};
    ParsedCurl out;
    size_t i = 1;
    for (; i < words.size(); i++) {
        const std::string &w = words[i];
        auto next = [&]() -> const std::string * {
            return i + 1 < words.size() ? &words[++i] : nullptr;
        };
        if (w == "-X" || w == "--request") {
            if (const std::string *v = next()) out.request.method = *v;
        } else if (w == "-H" || w == "--header") {
            if (const std::string *raw = next()) {
                size_t at = raw->find(':');
                if (at != std::string::npos && at > 0)
                    out.request.headers.push_back({trim(raw->substr(0, at)), trim(raw->substr(at + 1))});
            }
        } else if (w == "-u" || w == "--user") {
            if (const std::string *raw = next()) {
                size_t at = raw->find(':');
                out.request.auth = at == std::string::npos ? Auth{*raw, ""}
                                                           : Auth{raw->substr(0, at), raw->substr(at + 1)};
            }
        } else if (w == "-d" || w == "--data") {
            if (const std::string *v = next()) out.request.data = *v;
        }
        else if (w == "-I" || w == "--head") out.request.headOnly = true;
        else if (w == "-k" || w == "--insecure") out.request.insecure = true;
        else if (w == "-L" || w == "--location") out.request.followRedirects = true;
        else if (w == "--compressed") out.request.compressed = true;
        else if (!w.empty() && w[0] == '-') out.unknownFlags.push_back(w);
        else out.request.url = w;
    }
    if (out.request.url.empty()) return {std::nullopt, std::string("no URL found in command")};
    return {out, std::nullopt};
}

} // namespace curlbuilder

// Example:
// curlbuilder::shellQuote("it's") → "'it'\\''s'"
// curlbuilder::buildCurlCommand(req).command with req.url = "https://api.example.com",
//   req.method = "post", req.headers = {{"X-Tag", "it's"}}, req.data = "k=v"
// → "curl -X POST -H 'X-Tag: it'\\''s' -d 'k=v' 'https://api.example.com'"

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 →