一个使用 C++17 实现的轻量 HTTP/1.0 与 HTTP/1.1 请求解析器。HttpParser 支持增量输入:每次调用 parse() 都可以传入新收到的数据,并通过返回值判断是否需要继续接收、请求是否完成或报文是否无效。
- 解析请求行:方法、目标路径和 HTTP 版本。
- 解析请求头,并可通过
HttpRequest::getHeader()查询。 - 根据
Content-Length读取请求体。 - 支持请求行、请求头和请求体跨多次输入到达。
- 使用
reset()清除当前请求状态,开始解析新请求。
项目需要 CMake 3.16 及支持 C++17 的编译器。
cmake -S . -B build -DBUILD_TESTING=ON
cmake --build build
ctest --test-dir build --output-on-failure也可直接运行全部测试:
./build/main运行单个测试用例,例如:
./build/main headers_and_body_in_chunks#include "http_parse.h"
HttpParser parser;
const auto result = parser.parse(
"GET /health HTTP/1.1\r\n"
"Host: localhost\r\n"
"\r\n");
if (result == HttpParser::ParseResult::Complete)
{
const HttpRequest& request = parser.request();
// request.method() == "GET"
// request.target() == "/health"
}ParseResult::NeedMoreData 表示保留当前状态并继续传入后续字节;BadRequest 表示请求格式不合法。当前实现仅处理由 Content-Length 指定长度的请求体,不支持分块传输编码。
include/:对外头文件。src/:解析器与请求对象实现。tests/main.cc:CTest 注册的轻量测试程序。