Expand description
Middleware as values — MiddlewareStack and IntoMiddlewareStack.
In a name-keyed kernel a route names its middleware — middleware("auth")
— resolved through an alias map at runtime. That map is the only thing
standing between a typo and a route that runs unguarded, and a dynamic
language has no better option.
Rust does. A route takes the middleware itself:
let stack = MiddlewareStack::from(AddHeaders::security_defaults())
.with(ThrottleRequests::per_minute(60));
assert_eq!(stack.len(), 2);There is nothing to misspell, nothing to register, and nothing to look up. Deleting a middleware breaks every route that used it, in the compiler, naming each one.
§Groups are functions, not names
Elsewhere, web and api groups are keys in a map. Here a group is a
function that returns a stack — so it is discoverable by “go to definition”,
it can take arguments, and calling one that does not exist is a compile
error:
pub fn api(per_minute: u32) -> MiddlewareStack {
MiddlewareStack::new()
.with(HandleCors::any_origin())
.with(ThrottleRequests::per_minute(per_minute))
}
pub fn web() -> MiddlewareStack {
MiddlewareStack::new().with(AddHeaders::security_defaults())
}
assert_eq!(api(60).len(), 2);Nesting one group inside another is with_stack,
and a cycle is not expressible — a function cannot call itself into a value
without recursing forever, which is a stack overflow the type system already
prevents you from writing by accident, rather than a runtime check the old
registry had to perform.
§When the middleware needs the container
Some middleware cannot be built while routes are being declared: an
authentication guard needs the AuthManager the application binds, and the
container is not populated yet. That is the one case the old
name-and-factory indirection genuinely solved.
resolved solves it without a name. The
closure runs when the router compiles, which is after the container is
populated and still before the first request:
MiddlewareStack::new()
.resolved(|auth: Arc<AuthManager<User>>| Authenticate::new(auth))The container arrives as an argument rather than through a global. That is the difference between a builder you can call in a test and one that panics unless a process-wide slot happens to be filled — and it is the same reason the names went: a value handed to you is checkable, a value looked up is not.
A failure fails the boot, naming the middleware’s type and the route that wanted it.
Structs§
- Middleware
Stack - An ordered list of middleware, outermost first.
Traits§
- Into
Middleware Stack - Anything that can be attached where middleware is expected.