Type-indexed, per-request storage: middleware that computes something for later middleware or the handler (the authenticated user, a tenant, a DB transaction, request timing) stashes it here instead of a header, a global, or a new fixed field on HttpRequest.
More...
Type-indexed, per-request storage: middleware that computes something for later middleware or the handler (the authenticated user, a tenant, a DB transaction, request timing) stashes it here instead of a header, a global, or a new fixed field on HttpRequest.
At most one value per type T. HttpRequest::context holds one of these, and HttpRequest has matching set/get/ensure templates that forward to it, so a middleware writes req.set(AuthInfo{...}) and a handler reads req.get<AuthInfo>().
struct AuthInfo { std::string user_id; };
app.use([](
HttpRequest& req, std::shared_ptr<ResponseWriter> w) {
req.
set(AuthInfo{user_id});
return true;
});
app.get("/me", [](HttpRequest& req, std::shared_ptr<ResponseWriter> w) {
if (auto* auth = req.get<AuthInfo>()) {
w->send(HttpResponse().send(auth->user_id));
}
});
Represents an incoming HTTP request.
Definition HttpRequest.hpp:54
T & set(T value)
context.set<T>(value): see RequestContext::set.
Definition HttpRequest.hpp:83
The first few distinct types used (4, kept inline) cost no heap allocation beyond whatever std::any itself needs to hold the value (none for a value that fits its small-object buffer: a pointer, a shared_ptr, a small struct). A fifth distinct type moves into a heap-allocated overflow list, grown one slot at a time (std::deque, not std::vector: a pointer or reference once returned by get/ensure stays valid for the rest of the request, including across later set, erase or ensure calls for other types — a growing vector would invalidate it on reallocation). A slot a type was erased from is reused by the next type that needs one, rather than left to grow the storage further.
T must be copy-constructible (a std::any requirement), as most context values are: an id, a small struct, a shared_ptr to something with its own lifetime (a DB transaction, say). A move-only type does not fit here; wrap it in a shared_ptr instead. T = std::any itself is rejected at compile time: assigning it into the slot's own std::any would merge the two rather than nest one inside the other.
Not thread-safe: as with the rest of HttpRequest, only the thread currently handling the request should read or write it.