Module http::router
HTTP routing and middleware.
A Router maps (method, path pattern) to handlers — patterns as in std/http/route.h (":id" captures a segment, "*" / "*rest" the rest of the path) — runs a middleware chain around them, and serves itself on an HttpServer (std/http/http.h):
struct HttpResponse get_user(&HttpRequest req, &HttpCtx ctx) {
return std::HttpResponse::text(200, ctx.param_or("id", "?"));
}
struct Router r = std::Router::new();
r.use_logger();
r.use_cors("*", "GET, POST", "Content-Type");
r.get("/users/:id", get_user);
r.static_dir("/assets", "./public");
struct HttpServerConfig cfg = std::HttpServerConfig::defaults(8080);
r.listen(&cfg); // or r.start(&srv) + srv.stop()
Matching. The most specific matching route wins (literal segments beat ":param", which beats "*"), whatever the registration order. A path that matches some route but not for this method gets 405 with an Allow header (HEAD falls back to a GET route; OPTIONS without a route of its own answers 204 with Allow); no match at all gets the not-found handler (a plain 404 by default).
Middleware is fn(req, ctx, next): call next.run(req, ctx) to continue down the chain (and eventually to the route), or return a response of your own to short-circuit. Middleware runs in registration order for every request, matched or not, and sees ctx.params of the matched route.
Handlers are plain function pointers (no closures), so per-application state lives in globals or in what the handler can reach from the request; ctx.state (set_state) carries one pointer-sized value for the whole router.
Structs
| HttpCtx | Per-request context passed to route handlers and middleware. |
| HttpNext | The rest of the middleware chain. |
| Router |
Type aliases
| RouteHandler | |
| Middleware |
Functions
| router_set_state | Stores/reads the router's one application pointer (shared by every request; synchronize it yourself if handlers mutate what it points at). |
| router_state | |
| http_conn_none | A ready-made HttpConn for calling Router::dispatch outside a server (fd -1, nothing detachable). |