C++ HTTP Fundamentals: Parsing, Headers, Chunked Encoding, Beast [#30-1]
이 글의 핵심
Stop hand-rolling HTTP parsing—use Beast buffers, limits, and timeouts for safe servers and clients.
Introduction: manual HTTP parsing is bug-prone
Parsing pitfalls
Naïvely splitting on spaces breaks on multiple spaces, tabs, CRLF vs LF, chunked bodies, and multi-packet reads. Content-Length mismatches cause infinite read waits without timeouts.
Fix: Boost.Beast (http::read, flat_buffer, body_limit, expires_after), RFC 7230 semantics.
Goals: message layout, headers, Transfer-Encoding: chunked, Beast APIs, common errors, keep-alive buffer hygiene, CRLF injection hardening.
Requires: Boost.Beast 1.70+, Boost.Asio 1.70+.
HTTP message shape
Request: request line → headers → blank line → body (length via Content-Length or chunked).
Response: status line → headers → body.
Refer to the mermaid diagrams and hex sketches earlier in this article.
Parsing helpers (educational)
The article shows small C++ helpers for request line, status line, header map, Content-Length, chunk decoder—use them to learn, but prefer Beast in production.
Beast
http::async_read/http::readontcp_stream+flat_buffer.prepare_payload()after setting body.body_limit,header_limitagainst DoS.dynamic_body/file_bodyfor large uploads instead ofstring_body.
The full HttpSession example matches the walkthrough in this post.
Common errors
- end_of_stream / connection_reset — treat as normal teardown.
- body limit exceeded — raise
body_limit. - partial message — timeouts + Beast parsing.
- Keep-alive —
req_ = {},buffer_.consumebetween reads. - Header injection — strip CR/LF from untrusted header values.
Production patterns
Request logging, size limits, graceful shutdown, connection pools (client), /health, CORS headers.
Checklist
- Beast read/write
- Limits + timeouts
-
prepare_payload - Keep-alive buffer reset
- No CRLF injection
References
Keywords
HTTP, Boost.Beast, chunked encoding, Asio, REST, HTTP/1.1