Middleware Chain Execution Order in Go: Request Mutation, Context Poisoning, and the Handler Boundary Contract
Middleware in Go's net/http ecosystem looks deceptively simple: wrap a http.Handler , do work before and after calling ServeHTTP , done. In practice, the execution model has enough sharp edges to cause authentication bypasses, incorrect distributed traces, and silent data corruption in multi-tenant microservices. The problem is not any individual middleware—it is the implicit contract about what each layer is permitted to read, mutate, and propagate, and in what order those permissions compose.
The Execution Model Is Not a Pipeline
Most engineers think of middleware as a linear pipe. The mental model is A → B → C → handler → C → B → A . That is true for the call stack, but it obscures the actual mechanics.
Each middleware receives the same http.ResponseWriter interface and *http.Request pointer. The request body is a one-read stream. The response writer is stateful. Neither is a copy.…