Middleware
Middleware is a function that wraps another function, usually an http.Handler, to run code before and after the inner call. Logging, auth, and request IDs are middleware. The same wrapping idea applies to any func(T) error.
Detailed Explanation
http.Handler is ServeHTTP(ResponseWriter, *Request). Middleware is func(http.Handler) http.Handler. The returned handler does setup, calls next.ServeHTTP, then teardown. You stack them: log(auth(mux)). The outer wrapper runs first on the way in and last on the way out, like defer.
This page is the general pattern. HTTP-specific wiring (ListenAndServe, ServeMux) lives under web. Here the point is composition: a small interface or function type plus wrappers that do not know the inner implementation.
Go style. Prefer func(http.Handler) http.Handler over a middleware interface with ten methods. A constructor func RequestID(next http.Handler) http.Handler is enough. Share values through context.WithValue on the request, not through globals.
Not only HTTP. A func(ctx context.Context, req Req) (Resp, error) can be wrapped the same way for retries, metrics, and tracing. The name "middleware" in Go still most often means HTTP.
What it costs. Each wrapper is a closure and a call. A stack of five is fine. A stack that allocates a huge wrapper state per request shows up in profiles. Keep middleware cheap on the success path; do I/O (auth server) only when you must, and honour Request.Context().
Code Examples
package main
import (
"log"
"net/http"
"time"
)
func Logger(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
next.ServeHTTP(w, r)
log.Println(r.Method, r.URL.Path, time.Since(start))
})
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("GET /health", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
})
http.ListenAndServe(":8080", Logger(mux))
}type Middleware func(http.Handler) http.Handler
func chain(h http.Handler, ms ...Middleware) http.Handler {
for i := len(ms) - 1; i >= 0; i-- {
h = ms[i](h)
}
return h
}Common Gotchas
Reading `r.Body` in middleware consumes it for the handler
tee or restore if both need it.
Order is outside-in
the first wrapper in `chain` is the outermost if you apply from the end of the slice.
HTTP route middleware is `http-middleware` in this glossary
this term is the wrapping pattern.