HTTP Middleware Chain Composition
Compose request middleware as http.Handler wrappers so logging, recovery, and auth stack in a readable order.
Code
package main
import (
"log"
"net/http"
"time"
)
type middleware func(http.Handler) http.Handler
func chain(h http.Handler, mws ...middleware) http.Handler {
// 逆序包裹:第一个 middleware 在最外层
for i := len(mws) - 1; i >= 0; i-- {
h = mws[i](h)
}
return h
}
func logging(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
next.ServeHTTP(w, r)
log.Printf("%s %s took %s", r.Method, r.URL.Path, time.Since(start))
})
}
func recovery(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
if rec := recover(); rec != nil {
log.Printf("panic recovered: %v", rec)
http.Error(w, "internal error", http.StatusInternalServerError)
}
}()
next.ServeHTTP(w, r)
})
}
func main() {
handler := chain(
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("ok"))
}),
logging,
recovery,
)
log.Println("middleware chain ready:", handler != nil)
}Behavior at a glance
Count the functions chain, logging, recovery and main as the entire surface area of HTTP Middleware Chain Composition.
Iteration happens inside for i := len(mws) - 1; i >= 0; i-- — everything outside it runs once. The cleanup call is deferred to function exit — success, early return, and panic all covered.
Applying it
Entry signature: func chain(h http.Handler, mws ...middleware) http.Handler
Launch the file; main takes over and steps through chain.
Statements that matter
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
next.ServeHTTP(w, r)
log.Printf("%s %s took %s", r.Method, r.URL.Path, time.Since(start))
})
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
if rec := recover(); rec != nil {
log.Printf("panic recovered: %v", rec)
http.Error(w, "internal error", http.StatusInternalServerError)
}
}()
next.ServeHTTP(w, r)
})
func chain(h http.Handler, mws ...middleware) http.Handler {
// 逆序包裹:第一个 middleware 在最外层
for i := len(mws) - 1; i >= 0; i-- {
h = mws[i](h)
}
return h
}
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.Accept Header ParserParse an Accept header into media ranges with their quality values and specificity, sorted by preference for content negotiation debugging.Basic & Bearer Auth Header ToolEncode and decode HTTP Authorization Basic and Bearer headers locally with UTF-8 Base64 validation and automatic JWT claim and expiry inspection.
FAQ
- How do you run HTTP Middleware Chain Composition?
- Execute it straight away — the program needs nothing beyond the runtime.
Report a problem with this exampleOpens a pre-filled issue on GitHub.