HTTP Middleware Chain (Rust)
Topics: middleware, function composition, Service/Layer
Problem
Compose a list of middlewares around a handler. A handler is a Service
(Request -> Response); a middleware wraps one handler and returns a new one — the synchronous
analog of Go's func(http.Handler) http.Handler, the same shape tower/axum are built on (you
implement it, no framework).
pub trait Service { fn call(&self, req: Request) -> Response; }
pub type BoxService = Box<dyn Service>;
pub type Middleware = Box<dyn Fn(BoxService) -> BoxService>;
pub fn chain(handler: BoxService, middlewares: Vec<Middleware>) -> BoxService;
- Middlewares run left-to-right on the way in and right-to-left on the way out:
chain(h, [A, B, C]) has the same call order as A(B(C(h))) — A is outermost.
- A middleware may short-circuit by returning a response without calling its inner service.
- Zero middlewares returns the handler unchanged.
chain(h, [A, B, C]).call(req)
→ A-in, B-in, C-in, handler, C-out, B-out, A-out
Key concepts
- Wrap in reverse: fold the middlewares from last to first so the first one ends up outermost.
Service + HandlerFn: a handler is Request -> Response; HandlerFn adapts a closure into
a Service. A middleware receives the next BoxService and returns a new one that calls it (or
doesn't).
- Short-circuit: a middleware that returns its own
Response and drops next stops the chain.
Grading
Your solution.rs is compiled together with a trusted tests.rs (which include!s it) using
rustc --test. Only solution.rs is yours to edit.
Sign in to submit your solution.