HTTP messages and handlers¶
Overview¶
The protocol-independent part of HTTP: the request and response types, the handler type and the router that HTTP/1, HTTP/2 and HTTP/3 all use, so one handler serves every protocol version.
| Header | Package config |
|---|---|
<pace/http.hpp> |
always included (header-only) |
The named module is pace.http. Everything is in namespace pace::http; pace::http1 is an alias of the same
namespace. The module has no network code. Each protocol module adds its own server and clients on top of these
types:
| Protocol | Header | Namespace | Reference |
|---|---|---|---|
| HTTP/1.0 and HTTP/1.1 | <pace/http1.hpp> |
pace::http |
HTTP/1 |
| HTTP/2 | <pace/http2.hpp> |
pace::http2 |
HTTP/2 |
| HTTP/3 | <pace/http3.hpp> |
pace::http3 |
HTTP/3 |
Pages of this module:
| Page | Contents |
|---|---|
| This page | header_field, request, response, text/html/json, protocol_error, handler |
| Routing | make_handler, router: handler adapters and exact routing |
| URL clients | get/post/fetch and async_get/async_post/async_fetch across HTTP/1, HTTP/2 and HTTP/3 |
Synopsis¶
#include <pace/http.hpp>
#include <pace/runtime.hpp>
int main()
{
pace::http::router routes;
routes.get("/hello", [] { return pace::http::text("hello\n"); });
// The same router can be passed to pace::http::serve, pace::http2::serve or pace::http3::serve.
// Here it is called directly.
auto reply = pace::run(routes(pace::http::request{.method = "GET", .target = "/hello"}));
return reply.status == 200 && reply.body == "hello\n" ? 0 : 1;
}
Types¶
header_field¶
One header or trailer field. Both strings own their contents. Names keep the spelling they had on the wire or that the application gave them; HTTP/2 and HTTP/3 deliver lowercase names. Duplicate fields are kept as separate entries, in order; PACE never combines them.
header_map¶
Headers and trailers preserve insertion order and store the first field inline. Append fields with
push_back({name, value}). Use find(name) for a case-insensitive pointer to the first field, or end() on
a miss. Common names such as header_names::set_cookie are available as constants. Iterate the map to read
every occurrence of a repeated field.
request¶
struct request
{
std::string method;
std::string target;
std::string version;
header_map headers{};
std::string body;
bool keep_alive = true;
header_map trailers{};
bool chunked = false;
[[nodiscard]] std::string_view header(std::string_view name) const noexcept;
};
| Member | Meaning |
|---|---|
method |
Method token as sent, case-sensitive (GET, POST, …) |
target |
Request target in origin form, path plus optional query (/a/b?x=1). Never URL-decoded |
version |
HTTP/1.0 or HTTP/1.1 on HTTP/1, HTTP/2 or HTTP/3 on received HTTP/2 and HTTP/3 requests. An HTTP/1 client treats an empty version as HTTP/1.1 |
headers |
Header fields other than the ones the protocol manages. On a received HTTP/2 or HTTP/3 request the :authority pseudo-header appears as a host field |
body |
The complete body, already de-framed (no chunk boundaries); may hold binary bytes |
keep_alive |
HTTP/1 only: whether the connection stays open after this exchange |
trailers |
Trailer fields, kept separate from headers |
chunked |
HTTP/1 only: the body was, or is to be, sent with chunked transfer coding |
header(name) returns the value of the first field in headers whose name equals name ignoring ASCII case,
or an empty view when there is none, so a missing field and an empty one look the same. The view points into
the request; copy it before the request changes or is destroyed. Trailers are not searched.
response¶
struct response
{
unsigned status = 200;
std::string body;
std::string content_type = "text/plain; charset=utf-8";
header_map headers{};
bool close = false;
std::string version = "HTTP/1.1";
header_map trailers{};
bool chunked = false;
std::optional<std::uint64_t> representation_length{};
[[nodiscard]] std::string_view header(std::string_view name) const noexcept;
};
| Member | Meaning |
|---|---|
status |
Status code. A server response must be in [200, 599] |
body |
The complete body |
content_type |
Sent as the Content-Type field; an empty string sends none. On a received response it holds the peer's Content-Type value, or is empty. Set the content type here, never through headers |
headers |
Other header fields. Framing fields (Content-Length, Transfer-Encoding, Connection, Trailer) are generated by the protocol and must not be added |
close |
HTTP/1 only. On a server response, true closes the connection after it. On a received response, true means the connection cannot be reused |
version |
On a received response, the peer's version (HTTP/1.0, HTTP/1.1, HTTP/2, HTTP/3). Ignored on a server response: the HTTP/1 server always writes an HTTP/1.1 status line |
trailers |
Trailer fields. HTTP/1 sends them only with chunked = true |
chunked |
HTTP/1 only: send the body with chunked transfer coding; on a received response, whether it arrived chunked |
representation_length |
HTTP/1 only, for a reply to HEAD: the Content-Length to announce when body is empty. Used by the reverse proxy; ignored for responses that carry a body |
header(name) behaves as on request.
Fields marked "HTTP/1 only" are ignored by HTTP/2 and HTTP/3, which have no connection-level framing per message. The rules each protocol applies when it writes and reads these fields are on its own page.
protocol_error¶
class protocol_error : public std::runtime_error
{
public:
explicit protocol_error(const std::string& message);
};
Thrown by a client when the peer's response is malformed, truncated or larger than the configured limits. The
connection is closed when it is thrown. Transport failures, including cancellation, are std::system_error
instead.
handler¶
The server-side handler of HTTP/1, HTTP/2 and HTTP/3. It receives the complete request by value and returns a
task that produces the complete response. Write one directly as a coroutine taking request, or let
make_handler or router adapt a lambda that returns response or task<response>. The HTTP/1
server also accepts a server_handler that can stream its response; see HTTP/1 server.
The shared router also accepts a streaming handler that receives a request head, a body_reader and a body_writer. Streaming routes
pace::http1¶
An alias that names the HTTP/1 version explicitly: pace::http1::get and pace::http::get are the same function.
Functions¶
text, html, json¶
inline response text(std::string body, unsigned status = 200);
inline response html(std::string body, unsigned status = 200);
inline response json(std::string body, unsigned status = 200);
Return a response that owns body, with the given status and a content type of text/plain; charset=utf-8,
text/html; charset=utf-8 or application/json. They do not escape, serialize or validate anything: json
takes text that is already JSON. Every other field keeps its default and can be changed on the result.
The routing functions make_handler and router are on the routing page.
Errors¶
The types and helpers on this page throw nothing beyond std::bad_alloc. protocol_error is the exception the
clients use for a malformed peer response. What each server does with an exception thrown by a handler is on its
protocol page; the HTTP/1 server answers with a 500 and closes the connection.
Threads and concurrency¶
request and response are plain values with no thread affinity. A server copies its handler into every
connection, and the copies can run at the same time on different worker threads, so state that the handler's
captures share must be synchronized by the application.
Lifetime and ownership¶
Every message member owns its data. Views returned by header() borrow from the message. A handler receives its
request by value and owns it for the whole coroutine; it may move from it freely.
Limits and defaults¶
| Item | Default |
|---|---|
response::status |
200 |
response::content_type |
text/plain; charset=utf-8 |
response::version |
HTTP/1.1 |
request::keep_alive |
true |
request::chunked, response::chunked, response::close |
false |
Size limits on received messages belong to each protocol: http::limits for HTTP/1, http2::limits and
http3::limits.
See also¶
- Routing and URL clients
- HTTP/1, HTTP/2, HTTP/3
- Gateway services
- Tutorial: HTTP client, HTTP server
- HTTP recipes