蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

离线实测 C++17 CGI HTTP 响应头组装、环境变量与 QUERY_STRING/POST/Cookie 解析

CPP本地离线 Docker 容器(mstorsjo/llvm-mingw:20260616,G++ 13.3.0 C++17 linux/amd64,--network none)。explore-cpp-web-programming.cpp
explore-cpp-web-programming.cpp209 行
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <map>
#include <sstream>
#include <string>
#include <vector>

namespace lab {

struct Case {
    std::string name;
    std::string expected_json;
    std::string actual_json;
    bool passed;
};

std::string esc(const std::string& s) {
    std::string out = "\"";
    for (unsigned char c : s) {
        switch (c) {
            case '\"': out += "\\\""; break;
            case '\\': out += "\\\\"; break;
            case '\b': out += "\\b"; break;
            case '\f': out += "\\f"; break;
            case '\n': out += "\\n"; break;
            case '\r': out += "\\r"; break;
            case '\t': out += "\\t"; break;
            default:
                if (c < 0x20) {
                    char buf[8];
                    std::snprintf(buf, sizeof(buf), "\\u%04x", c);
                    out += buf;
                } else {
                    out += static_cast<char>(c);
                }
        }
    }
    out += "\"";
    return out;
}

std::string jbool(bool v) { return v ? "true" : "false"; }

void emit(const std::vector<Case>& cases) {
    std::cout << "{\"runtime\": \"G++ C++17 (mstorsjo/llvm-mingw:20260616)\", \"cases\": [";
    for (std::size_t i = 0; i < cases.size(); ++i) {
        if (i) std::cout << ", ";
        std::cout << "{\"name\": " << esc(cases[i].name)
                  << ", \"expected\": " << cases[i].expected_json
                  << ", \"actual\": " << cases[i].actual_json
                  << ", \"passed\": " << jbool(cases[i].passed) << "}";
    }
    std::cout << "]}\n";
}

int hex_val(char ch) {
    if (ch >= '0' && ch <= '9') return ch - '0';
    if (ch >= 'a' && ch <= 'f') return ch - 'a' + 10;
    if (ch >= 'A' && ch <= 'F') return ch - 'A' + 10;
    return -1;
}

std::string url_decode(const std::string& s) {
    std::string out;
    for (std::size_t i = 0; i < s.size(); ++i) {
        if (s[i] == '+') {
            out += ' ';
        } else if (s[i] == '%' && i + 2 < s.size()) {
            int hi = hex_val(s[i + 1]);
            int lo = hex_val(s[i + 2]);
            if (hi >= 0 && lo >= 0) {
                out += static_cast<char>((hi << 4) | lo);
                i += 2;
            } else {
                out += s[i];
            }
        } else {
            out += s[i];
        }
    }
    return out;
}

std::map<std::string, std::string> parse_urlencoded(const std::string& qs) {
    std::map<std::string, std::string> kv;
    std::istringstream iss(qs);
    std::string pair;
    while (std::getline(iss, pair, '&')) {
        if (pair.empty()) continue;
        std::size_t eq = pair.find('=');
        if (eq == std::string::npos) {
            kv[url_decode(pair)] = "";
        } else {
            kv[url_decode(pair.substr(0, eq))] = url_decode(pair.substr(eq + 1));
        }
    }
    return kv;
}

std::string trim(const std::string& s) {
    std::size_t b = 0;
    while (b < s.size() && (s[b] == ' ' || s[b] == '\t' || s[b] == '\r' || s[b] == '\n')) ++b;
    std::size_t e = s.size();
    while (e > b && (s[e - 1] == ' ' || s[e - 1] == '\t' || s[e - 1] == '\r' || s[e - 1] == '\n')) --e;
    return s.substr(b, e - b);
}

std::map<std::string, std::string> parse_cookies(const std::string& header) {
    std::map<std::string, std::string> kv;
    std::istringstream iss(header);
    std::string item;
    while (std::getline(iss, item, ';')) {
        std::size_t eq = item.find('=');
        if (eq != std::string::npos) {
            kv[trim(item.substr(0, eq))] = trim(item.substr(eq + 1));
        }
    }
    return kv;
}

} // namespace lab

int main() {
    std::vector<lab::Case> cases;

    // Case 1: CGI HTTP headers and HTML response framing
    std::string body = "<html><head><title>CGI</title></head><body><h2>Hello CGI</h2></body></html>\n";
    std::ostringstream resp;
    resp << "Content-Type: text/html; charset=utf-8\r\n"
         << "Content-Length: " << body.size() << "\r\n"
         << "\r\n"
         << body;
    std::string raw = resp.str();
    std::size_t sep = raw.find("\r\n\r\n");
    bool header_ok = (sep != std::string::npos) &&
                     (raw.substr(0, sep).find("Content-Type: text/html") != std::string::npos) &&
                     (raw.substr(sep + 4) == body);
    cases.push_back({
        "cgi_http_header_and_html_response",
        lab::jbool(true),
        lab::jbool(header_ok),
        header_ok
    });

    // Case 2: CGI environment variables & GET QUERY_STRING parsing
    setenv("REQUEST_METHOD", "GET", 1);
    setenv("QUERY_STRING", "first_name=ZARA&last_name=ALI&city=New+York%21", 1);
    setenv("SCRIPT_NAME", "/cgi-bin/cpp_get.cgi", 1);
    const char* method = std::getenv("REQUEST_METHOD");
    const char* qs = std::getenv("QUERY_STRING");
    const char* script = std::getenv("SCRIPT_NAME");
    auto get_params = lab::parse_urlencoded(qs ? qs : "");
    std::string get_summary = std::string(method ? method : "") + ":" +
                              get_params["first_name"] + "," +
                              get_params["last_name"] + "," +
                              get_params["city"] + ":" +
                              (script ? script : "");
    std::string exp_get = "GET:ZARA,ALI,New York!:/cgi-bin/cpp_get.cgi";
    cases.push_back({
        "cgi_env_and_query_string_parse",
        lab::esc(exp_get),
        lab::esc(get_summary),
        get_summary == exp_get
    });

    // Case 3: POST form controls (checkbox, radio, textarea, dropdown) & multipart boundary detection
    std::string post_body = "maths=on&subject=maths&textcontent=Line1%0ALine2&dropdown=Maths";
    auto post_params = lab::parse_urlencoded(post_body);
    bool maths_checked = post_params.count("maths") > 0 && post_params["maths"] == "on";
    bool physics_checked = post_params.count("physics") > 0;
    std::string ct = "multipart/form-data; boundary=----CgiBoundary123";
    std::size_t bpos = ct.find("boundary=");
    std::string boundary = (bpos != std::string::npos) ? ct.substr(bpos + 9) : "";
    bool post_ok = maths_checked && !physics_checked &&
                   post_params["subject"] == "maths" &&
                   post_params["textcontent"] == "Line1\nLine2" &&
                   post_params["dropdown"] == "Maths" &&
                   boundary == "----CgiBoundary123";
    cases.push_back({
        "cgi_post_form_controls_parse",
        lab::jbool(true),
        lab::jbool(post_ok),
        post_ok
    });

    // Case 4: Set-Cookie generation before Content-Type and HTTP_COOKIE parsing
    std::ostringstream cookie_resp;
    cookie_resp << "Set-Cookie: UserID=XYZ; Path=/; Secure; HttpOnly\r\n"
                << "Set-Cookie: Theme=dark; Path=/\r\n"
                << "Content-Type: text/html\r\n\r\nOK";
    std::string cstr = cookie_resp.str();
    bool set_before_ct = cstr.find("Set-Cookie:") < cstr.find("Content-Type:");
    setenv("HTTP_COOKIE", "UserID=XYZ; Theme=dark; Lang=zh", 1);
    auto cookies = lab::parse_cookies(std::getenv("HTTP_COOKIE"));
    std::string cookie_summary = (set_before_ct ? "before:" : "after:") +
                                 cookies["UserID"] + "/" + cookies["Theme"] + "/" + cookies["Lang"];
    std::string exp_cookie = "before:XYZ/dark/zh";
    cases.push_back({
        "cgi_cookie_set_and_parse",
        lab::esc(exp_cookie),
        lab::esc(cookie_summary),
        cookie_summary == exp_cookie
    });

    lab::emit(cases);
    return 0;
}
本例需在 本地离线 Docker 容器(mstorsjo/llvm-mingw:20260616,G++ 13.3.0 C++17 linux/amd64,--network none)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:本地离线 Docker 容器(mstorsjo/llvm-mingw:20260616,G++ 13.3.0 C++17 linux/amd64,--network none)。

入口文件:projects/cplusplus-cpp-web-programming-lab/explore-cpp-web-programming.cpp

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-cpp-web-programming.cpp,或下载右侧课程工程包。
  2. 确认本地已准备 本地离线 Docker 容器(mstorsjo/llvm-mingw:20260616,G++ 13.3.0 C++17 linux/amd64,--network none)。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:C++

课程关联工程包(登记关联99章) · 含当前章节或实例 · mbskycom202612a2307.zip

下载课程关联工程包:C++

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2405.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习