Composable HTTP Middleware Chain
Compose HTTP handlers through middleware that wrap the next handler, adding logging, recovery, and request identifiers without duplication.
Code
package main
import (
"log"
"net/http"
"time"
)
type Middleware func(http.Handler) http.Handler
func chain(h http.Handler, middleware ...Middleware) http.Handler {
for i := len(middleware) - 1; i >= 0; i-- {
h = middleware[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("method=%s path=%s duration=%s", r.Method, r.URL.Path, time.Since(start))
})
}
func recoverPanic(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
if rec := recover(); rec != nil {
http.Error(w, "internal error", http.StatusInternalServerError)
}
}()
next.ServeHTTP(w, r)
})
}How the snippet works
Composable HTTP Middleware Chain is built around the functions chain, logging and recoverPanic.
Repetition is confined to for i := len(middleware) - 1; i >= 0; i-- — the rest of the file is straight-line. A defer statement pins the cleanup to the function boundary rather than scattering it through the body.
Using it
Signature: func chain(h http.Handler, middleware ...Middleware) http.Handler
Key statements
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
next.ServeHTTP(w, r)
log.Printf("method=%s path=%s duration=%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 {
http.Error(w, "internal error", http.StatusInternalServerError)
}
}()
next.ServeHTTP(w, r)
})
func chain(h http.Handler, middleware ...Middleware) http.Handler {
for i := len(middleware) - 1; i >= 0; i-- {
h = middleware[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
- Any setup needed beyond the language runtime?
- None — the language runtime is the only requirement. Every import resolves inside the standard library — `log`, `net/http`, `time`. The file defines `chain`, `logging`, `recoverPanic` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.