Middleware
HTTP middleware is func(http.Handler) http.Handler that wraps a handler with cross-cutting behaviour: logs, auth, CORS, panic recovery, request IDs. The inner handler is next.
Detailed Explanation
net/http has no middleware type in the package. The community convention is a function that takes a handler and returns a handler. You apply them in main: handler := cors(auth(log(mux))). Each wrapper sees the request on the way in and the (already written) response on the way out, unless it uses a wrapping ResponseWriter to capture status.
Request-scoped values. r = r.WithContext(context.WithValue(r.Context(), key, id)) then next.ServeHTTP(w, r). Use an unexported key type so other packages cannot collide. Do not stash a *sql.DB in context; put that on the server struct.
Status capture. The standard ResponseWriter does not tell you the status after next returns unless you wrap it and override WriteHeader. Many logging middlewares do that. Remember to forward Unwrap / Flush if you need hijack or flush.
Recovery. Server already recovers panics. Custom recover middleware can write a JSON 500 with a request ID. Recover only in the same goroutine as ServeHTTP; it will not catch go func() { panic }().
What it costs. Same as the design-pattern term: a few closures. Auth middleware that calls an issuer on every request is the real cost. Honour r.Context() so cancelled requests do not keep doing auth work.
Code Examples
package main
import (
"context"
"net/http"
)
type ctxKey int
const reqIDKey ctxKey = 1
func RequestID(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
id := r.Header.Get("X-Request-ID")
if id == "" {
id = "generated"
}
ctx := context.WithValue(r.Context(), reqIDKey, id)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
func main() {
mux := http.NewServeMux()
http.ListenAndServe(":8080", RequestID(mux))
}Common Gotchas
Apply order is outside-in
the first wrapper you apply last is the outermost if you nest calls.
The general wrapping idea is `design-patterns/middleware`
The general wrapping idea is `design-patterns/middleware`