第 4 章:请求、JSON 与响应
本章介绍 method、path、query、header 和 body 的读取方式,以及文本、JSON、错误状态与重定向响应。
1. 请求对象包含什么
| 字段/方法 | 含义 |
|---|---|
type | HTTP method,例如 GET、POST。 |
locPara | 原始 path 与 query,例如 /users?id=7。 |
loc | 仅 path,例如 /users。 |
para | 从问号开始的原始 query 字符串,例如 ?id=7;不会自动 URL decode,也不是键值字典。 |
header | 完整请求头字符串。 |
headerValue(name) | 大小写不敏感读取 header,返回非拥有 string_view。 |
bodyView() | 统一读取 Content-Length 或 chunked body,返回非拥有 string_view。 |
2. 视图的生命周期
// 只在当前回调里使用可以保留 string_view。
const std::string_view view = request.bodyView();
// 跨回调、Worker、容器或异步任务使用时,将视图复制为拥有数据的 string。
const std::string body(request.bodyView());3. 解析客户端 JSON
完整示例在 examples/http_json.cpp,它演示 method 检查、JsonCpp 解析、400 语法错误、422 字段校验和 201 成功响应。
const std::string body(request.bodyView());
Json::CharReaderBuilder builder;
auto reader = std::unique_ptr<Json::CharReader>(builder.newCharReader());
Json::Value input;
std::string error;
if(!reader->parse(body.data(), body.data() + body.size(), &input, &error))
return client.sendJson(makeError("invalid JSON"), "400 Bad Request") ? 1 : -2;4. 常用响应
client.sendText("created", "201 Created");
client.sendJson(value, "200 OK");
client.redirect("/login", "302 Found");5. 运行 Demo
./build/examples/sttnet_http_json
curl -i 'http://127.0.0.1:8081/inspect?source=guide' \
-H 'Content-Type: text/plain' --data 'hello'
curl -i -X POST http://127.0.0.1:8081/json \
-H 'Content-Type: application/json' \
--data '{"name":"Stephen"}'
# 故意发送错误 JSON
curl -i -X POST http://127.0.0.1:8081/json \
-H 'Content-Type: application/json' --data '{bad json}'