Expand description
An ergonomic routing layer (feature router).
Router dispatches a request to one of several handlers by HTTP method and
path pattern, the way axum / actix-web users expect:
use httpsd::{Request, Response, StatusCode};
use httpsd::router::Router;
let app = Router::new()
.get("/", |_req: &Request| "hello world")
.get("/users/:id", |req: &Request| {
format!("user {}", req.param("id").unwrap_or("?"))
})
.post("/users", |_req: &Request| (StatusCode::CREATED, "created"))
.fallback(|_req: &Request| (StatusCode::NOT_FOUND, "nope"));
server.handler(app)A Router is a Handler, so hand it straight to
Server::handler. Route handlers are looser
than the bare Handler trait: they can return anything that implements
IntoResponse — &str, String, Vec<u8>, a StatusCode, a
(StatusCode, T) pair, an Option<T>, or a Result<T, E> (so ? works in
a handler) — not just a fully-built Response.
Path patterns are split on /. A :name segment captures one path segment
(read it back with Request::param); a trailing *name captures the rest
of the path. Everything else matches literally. Leading and trailing slashes
are ignored, so /a/b, a/b, and /a/b/ all match the pattern /a/b.
Structs§
- Router
- A request router: match by method and path, dispatch to a handler.
Traits§
- Into
Response - A value that can be turned into a
Response. - Route
Handler - A route handler: any
Fn(&Request) -> impl IntoResponse.