HTTP Middleware Chain
Source: Custom
Topics: http.Handler, http.HandlerFunc, function composition
Problem
Implement Chain that composes a slice of middlewares around an http.Handler.
A middleware is a function that wraps a handler and returns a new handler.
Requirements:
- Middlewares execute left-to-right on the way in and right-to-left on the way out.
Chain(h, A, B, C) must produce the same call order as A(B(C(h))).
- A middleware may short-circuit by writing a response and not calling
next.
- Zero middlewares returns the original handler unchanged.
Types:
type Middleware func(next http.Handler) http.Handler
func Chain(h http.Handler, middlewares ...Middleware) http.Handler
Key concepts
- Wrap in reverse: iterate middlewares from last to first so the first middleware is outermost.
- http.HandlerFunc: converts a plain
func(w, r) into an http.Handler — use it inside each middleware.
- Short-circuit: a middleware that calls
w.WriteHeader and returns without calling next stops the chain.
Run
go test -v -bench=. -benchmem ./challenges/networking/middleware-chain/
Sign in to submit your solution.