Middlewares: Chaining, Security Headers, CORS, Compression, Response Time, Rate Limiter, Logging, Recover
"Middleware functions take an http.Handler and return a new one that can run code before and/or after calling the original handler — or it can decide not to call the original handler at all." — Mat Ryer, "How I write HTTP services in Go after 13 years", Grafana Labs blog, 10 February 2024
Summary: In Go a middleware is a function of type func(http.Handler) http.Handler: it wraps the next handler, runs code before and after it, and may answer on its own. A service stacks a dozen of them (request ID, logging, recover, real IP, security headers, CORS, rate limiting, timeout, compression, metrics, body limit, authentication, CSRF) and the order of that stack decides what each layer can see. Focus: the middleware shape and a Chain helper, ordering rules, request IDs and context keys, the slog logging middleware and status capture by wrapping ResponseWriter, http.ResponseController and Unwrap, the recover middleware and http.ErrAbortHandler, timeouts, the OWASP security headers, CORS and preflights, gzip compression and its traps, real IP and X-Forwarded-For trust, per-client token-bucket rate limiting with 429 and Retry-After, Prometheus histograms, http.MaxBytesReader, authentication passing identity through context, http.CrossOriginProtection (Go 1.25), request coalescing with singleflight, testing with httptest, and how chi, gin and Laravel do the same. Learning goal: Write any middleware from scratch, put a production stack in the right order and defend each position, recognise the five classic bugs (lost status, broken Flush, * with credentials, leftmost-IP rate limiting, compressed Content-Length), and test the whole stack with httptest without a network.
This page owns HTTP middleware in Go: the pattern, the standard ones a service needs, and their exact headers and status codes. It does not re-teach its neighbours: the server, ServeMux 1.22 routing and the client are in net/http: Server, Client, 1.22 Routing; rate-limiting algorithms in Go (token bucket, fixed window, leaky bucket and x/time/rate in depth) are in Rate Limiting in Go, and the system-level comparison and distributed limits in Rate Limiting: Token Bucket, Leaky Bucket, Windows; deadlines and context values in context; log/slog itself in CLI Flags, Env & Logging; sessions, JWT and password hashing in Authentication in Go; cookies, sessions and the CORS model in Web Sessions, Cookies & CORS; XSS and CSRF as attacks in OWASP Top 10; metrics and tracing stacks in Observability; and gzip, Brotli and zstd as algorithms in Compression.
Facts below were checked against the Go 1.27 standard-library source on go.dev (net/http server.go, request.go, responsecontroller.go, csrf.go, httptest; pkg.go.dev returns 403 to scripted fetches), the Go 1.20, 1.22, 1.23 and 1.25 release notes, the source of golang.org/x/time/rate, golang.org/x/sync/singleflight, github.com/rs/cors, chi v5 middleware, gin and Prometheus client_golang, MDN's CORS guide and header references, the OWASP HTTP Headers and CSRF cheat sheets and the Secure Headers Project, RFC 6585, RFC 7239 and RFC 9110, breachattack.com, and the Laravel 13 middleware and routing docs. Snippets declare go 1.24 and pin golang.org/x/time v0.14.0 (v0.15.0 requires go 1.25), golang.org/x/sync v0.19.0, github.com/rs/cors v1.11.1 and github.com/prometheus/client_golang v1.23.2 (v1.24 requires go 1.25). The CSRF snippet uses a Go 1.25 API, so its files carry a //go:build go1.25 line. All 17 library packages were compiled, vetted and tested with -race on Go 1.27.4 (macOS), and cmd/server was run for the curl labs; numbers in the lab are from those runs. The Go-version requirements of the pinned and next dependency versions come from their go.mod files on proxy.golang.org (saved with the sources).
Page map
| If you are looking for | Go to |
|---|---|
| The tables you can memorise in one minute | Everything in one minute |
| Why cross-cutting code belongs in wrappers | Why it exists |
| Handler history: Go 1.0 to Go 1.25 | Where it comes from |
| A before/after service | Go |
The middleware shape func(http.Handler) http.Handler | The shape |
| Chaining and a Chain helper | Chaining |
| Ordering: which layer goes where | Ordering |
| Request ID | Request ID |
| Logging middleware (slog, status capture via wrapping ResponseWriter) | Logging |
| http.ResponseController and wrapped writers (Unwrap) | ResponseController |
| Recover middleware (panic, http.ErrAbortHandler) | Recover |
| Timeout middleware | Timeout |
| Security headers (Content-Security-Policy, Strict-Transport-Security, X-Content-Type-Options, X-Frame-Options, Referrer-Policy, Permissions-Policy) | Security headers |
| CORS (Origin, preflight OPTIONS, Access-Control-Allow-*, credentials, Vary: Origin) and rs/cors | CORS |
| Compression (gzip, Accept-Encoding, Content-Encoding, Vary, BREACH note, Content-Length removal) | Compression |
| Real IP and X-Forwarded-For trust | Real IP |
| Rate limiter middleware (x/time/rate per client, token bucket, 429, Retry-After) | Rate limiter |
| Response time / metrics middleware (Prometheus histogram) | Metrics |
| Request body size limit | Body limit |
| Authentication middleware passing identity via context; context keys (unexported type) | Authentication |
| http.CrossOriginProtection (Go 1.25) and CSRF | CSRF |
| Request coalescing | Coalescing |
| httptest for middleware | Testing |
| chi/gin middleware comparison | chi and gin |
| How net/http calls you, exact error texts | Mechanics |
| The classic bugs and their fixes | Solving the classic problems |
| What to use when | Choosing |
| Monolith to distributed system | In architecture |
| Reproduce it on your machine | Lab |
| Laravel middleware comparison | For PHP/Laravel developers |
Everything in one minute
The pattern. One type, three moves. Every row is unpacked in the concept catalogue.
| Move | Code shape | Example |
|---|---|---|
| Before | work, then next.ServeHTTP(w, r) | Set security headers, mint a request ID, start a timer |
| After | next.ServeHTTP(w, r), then work | Log status and duration, observe a histogram |
| Short-circuit | write a response and return without calling next | 401 without a token, 429 when the bucket is empty, 204 for a CORS preflight |
Replace r | next.ServeHTTP(w, r.WithContext(ctx)) | Put the request ID, principal or a deadline in the context |
Replace w | next.ServeHTTP(wrapped, r) | Capture the status code, gzip the body |
The standard stack, outermost first (the order of the After snippet).
| # | Middleware | Why here | Answers by itself with |
|---|---|---|---|
| 1 | Request ID | Everything below logs it | never |
| 2 | Logging (slog) | Sees the final status, including the 500 from recover | never |
| 3 | Recover | Inside logging, outside everything that can panic | 500 |
| 4 | Real IP | Before anything keyed by client IP | never |
| 5 | Security headers | Applies to every response, including errors below | never |
| 6 | CORS | Before auth: preflights carry no credentials | 204 for a preflight |
| 7 | Rate limiter | Cheap rejection before real work | 429 + Retry-After |
| 8 | Timeout | Budget for the handler only | 504 (via the handler) |
| 9 | Compression | Innermost body wrapper, closest to the bytes | never |
| route | Auth, body limit, CSRF | Only on routes that need them | 401/403, 413, 403 |
The status codes and headers you will see.
| Signal | Who sends it | Meaning |
|---|---|---|
500 Internal Server Error | Recover middleware | A handler panicked; the stack is in the log |
429 Too Many Requests + Retry-After: 2 | Rate limiter | Bucket empty; RFC 6585 says it "MAY include a Retry-After header" |
413 Request Entity Too Large | Body limit | http: request body too large from MaxBytesReader |
401 + WWW-Authenticate | Authentication | No or bad credentials |
403 Forbidden | Authorization, CrossOriginProtection | Known caller, not allowed; or a cross-origin unsafe request |
503 from http.TimeoutHandler, 504 from your own | Timeout | Budget spent |
204 with Access-Control-Allow-* | CORS | Preflight approved |
Vary: Origin, Vary: Accept-Encoding | CORS, compression | Caches must key on these request headers |
Content-Encoding: gzip, no Content-Length | Compression | Body is compressed; length unknown up front |
Why it exists
Every endpoint of an HTTP service needs the same dozen things that have nothing to do with its business logic: an ID to correlate logs, one log line with status and duration, protection against a panic taking the connection down, the security headers a browser expects, CORS answers for the SPA on another origin, a rate limit, a time budget, compression, metrics, a cap on body size, authentication. Written inside each handler, they drift: the handler added last month forgets nosniff, logs in a different shape and has no recover. The Before snippet's test demonstrates exactly that drift.
A middleware moves one concern into one wrapper applied in one place. Because http.Handler is a one-method interface, a wrapper is just a function from handler to handler, and the whole stack is ordinary function composition that the compiler checks.
| Concern inside each handler | Concern in middleware |
|---|---|
| Copied N times, drifts | Written once, applied to every route |
| Handler tests must mock logging, headers, auth | Handler tests test the handler; middleware has its own tests |
| Order of concerns is implicit and varies | Order is one readable list |
| Easy to skip for a quick endpoint | Opt-out is explicit (a separate route group) |
| No hidden behaviour | Behaviour is "around" the handler: you must know the stack to debug |
| No extra allocations | A wrapper or two per request (ns, not µs) |
An everyday picture. An airport. A passenger (the request) walks through check-in (request ID: the boarding pass number every later desk writes down), security screening (auth, body limit), passport control (CORS, CSRF), and a queue marshal who stops people when the gate is full (rate limiter), before reaching the gate (the handler). Any desk can turn the passenger back without them ever seeing the gate. On the way back from a cancelled flight the same desks are passed in reverse: the desk nearest the entrance is the first one seen and the last one left. We reuse this picture below.
Three common misunderstandings, up front
- "Middleware order does not matter much." It decides everything: with recover outside logging, logging never sees the 500 (logging must wrap recover); a rate limiter before real IP limits the load balancer; auth before CORS rejects every preflight.
- "A wrapper around
ResponseWriteris transparent." It hides every optional interface (Flusher,Hijacker) unless it implements them or exposesUnwrapforhttp.ResponseController. One careless logging wrapper breaks SSE and WebSockets for the whole service. - "CORS protects my API." CORS lets a server relax the browser's same-origin rule for reading responses; it does not stop a cross-site form POST from reaching the server. CSRF needs its own defence (
http.CrossOriginProtection, tokens,SameSitecookies).
Where it comes from
net/http has had the Handler interface and HandlerFunc adapter since Go 1.0 (March 2012), and the doc on Handler still says what a wrapper may rely on: "Returning signals that the request is finished; it is not valid to use the ResponseWriter or read from the Request.Body after or concurrently with the completion of the ServeHTTP call." The standard library ships a few middlewares of its own: http.StripPrefix, http.TimeoutHandler, http.MaxBytesHandler (Go 1.18) and, since Go 1.25, http.CrossOriginProtection.Handler. The community converged early on func(http.Handler) http.Handler as the shape: Goji, Negroni and Alice popularised chaining helpers; chi (whose middleware package says several of its middlewares were "derived from Goji's middleware") made the shape its native API; gin and echo chose their own context type instead.
Three later releases changed what a good middleware looks like. Go 1.20 added http.ResponseController, because, in the release notes' words, optional interfaces such as Flusher "are not discoverable and clumsy to use"; a wrapper that exposes Unwrap() http.ResponseWriter keeps them reachable. Go 1.22 added methods and wildcards to ServeMux patterns, which made per-route middleware on the standard mux practical, and Go 1.23 added Request.Pattern ("contains the ServeMux pattern (if any) that matched the request"). Go 1.25 added CrossOriginProtection, which "uses modern browser Fetch metadata, doesn't require tokens or cookies, and supports origin-based and pattern-based bypasses". Mat Ryer's 2024 post is the clearest statement of the style this page follows: a NewServer constructor that applies the top-level middleware, and middleware constructors that take dependencies and return func(h http.Handler) http.Handler.
Go
Before
Two handlers with the cross-cutting code inline. The first one copies CORS *, nosniff, a recover and a log line; the second, written later, forgets half of it and reads an unbounded body. It works on a quiet day, which is exactly the problem.
// Package before shows cross-cutting concerns copied into every handler:
// it works, but each new handler must remember all of them, and they drift.
package before
import (
"encoding/json"
"log"
"net/http"
"time"
)
// ListOrders does CORS, headers, logging and recovery inline.
func ListOrders(w http.ResponseWriter, r *http.Request) {
start := time.Now()
defer func() {
if v := recover(); v != nil {
log.Printf("panic: %v", v)
http.Error(w, "internal error", http.StatusInternalServerError)
}
}()
w.Header().Set("Access-Control-Allow-Origin", "*") // copied from a blog post
w.Header().Set("X-Content-Type-Options", "nosniff")
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode([]string{"order-1", "order-2"})
log.Printf("%s %s %v", r.Method, r.URL.Path, time.Since(start)) // status unknown
}
// CreateOrder was written later by someone else: no recover, no nosniff,
// no body limit, and the log line has a different shape.
func CreateOrder(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
var in map[string]any
if err := json.NewDecoder(r.Body).Decode(&in); err != nil { // unbounded body
http.Error(w, "bad json", http.StatusBadRequest)
return
}
w.WriteHeader(http.StatusCreated)
log.Println("created order")
}After
The same API with one stack in one place. Each line has a comment saying why it is where it is; the route group adds authentication and a body limit only where they apply.
// Package after builds the same API with one middleware stack applied in a
// single, readable place: the order below is the order a request sees.
package after
import (
"encoding/json"
"log/slog"
"net/http"
"net/netip"
"time"
"academy/middlewares/auth"
"academy/middlewares/bodylimit"
"academy/middlewares/chain"
"academy/middlewares/compress"
"academy/middlewares/cors"
"academy/middlewares/logging"
"academy/middlewares/ratelimit"
"academy/middlewares/realip"
"academy/middlewares/recoverer"
"academy/middlewares/requestid"
"academy/middlewares/secheaders"
"academy/middlewares/timeout"
)
// Deps are the dependencies of the HTTP layer.
type Deps struct {
Log *slog.Logger
Verify auth.Verifier
Origins map[string]bool
Proxies []netip.Prefix
PerIP *ratelimit.Limiter
Deadline time.Duration
}
// NewServer returns the root handler (Mat Ryer's NewServer shape).
func NewServer(d Deps) http.Handler {
mux := http.NewServeMux()
api := chain.Chain(
auth.Middleware(d.Verify), // only /api routes need identity
bodylimit.Middleware(1<<20),
)
mux.Handle("GET /api/orders", api(http.HandlerFunc(listOrders)))
mux.Handle("POST /api/orders", api(http.HandlerFunc(bodylimit.CreateOrder)))
mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) { _, _ = w.Write([]byte("ok")) })
return Stack(d)(mux)
}
// Stack is the global middleware chain, outermost first. It is exported so
// tests can wrap any handler (a panicking one, for example) with it.
func Stack(d Deps) func(http.Handler) http.Handler {
byIP := func(r *http.Request) string {
if a, ok := realip.From(r.Context()); ok {
return a.String()
}
return "unknown"
}
return chain.Chain(
requestid.Middleware, // 1. id first: everything below logs it
logging.Middleware(d.Log), // 2. wraps recover (3), so it logs the 500 recover writes
recoverer.Middleware(d.Log), // 3. inside logging, outside everything that can panic
realip.Middleware(d.Proxies...), // 4. before anything keyed by client IP
secheaders.Middleware(secheaders.API, secheaders.TLSOnly),
cors.Middleware(cors.Config{ // 6. before auth: preflights carry no token
AllowedOrigins: d.Origins, AllowedMethods: []string{"GET", "POST"},
AllowedHeaders: []string{"Authorization", "Content-Type"}, AllowCredentials: true, MaxAge: 600,
}),
d.PerIP.Middleware(byIP), // 7. cheap rejection before real work
timeout.Middleware(d.Deadline), // 8. budget for the handler
compress.Middleware, // 9. innermost wrapper of the body
)
}
func listOrders(w http.ResponseWriter, r *http.Request) {
p, _ := auth.PrincipalFrom(r.Context())
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]any{"owner": p.Subject, "orders": []string{"order-1"}})
}The end-to-end tests drive the real stack through httptest.NewServer: a preflight passes without a token, an authenticated GET is gzipped and carries the request ID and nosniff, and the third limited request from one IP gets 429 with Retry-After. Two more tests pin the ordering claims: with loopback trusted as a proxy, client 198.51.100.1 (by X-Forwarded-For) gets 200 200 429 while client 198.51.100.2 still gets 200 (this test fails if the limiter is moved before real IP, because every request then shares one key), and a panicking handler wrapped in Stack answers 500 and the log contains both panic in handler and status=500 (this test fails if logging and recover are swapped).
package after
import (
"bytes"
"log/slog"
"net/http"
"net/http/httptest"
"net/netip"
"strings"
"testing"
"time"
"academy/middlewares/auth"
"academy/middlewares/ratelimit"
)
func newTestServer(log *bytes.Buffer) http.Handler { return NewServer(testDeps(log)) }
func testDeps(log *bytes.Buffer) Deps {
return Deps{
Log: slog.New(slog.NewTextHandler(log, nil)),
Verify: auth.StaticTokens(map[string]auth.Principal{"t1": {Subject: "user:1"}}),
Origins: map[string]bool{"https://app.example.test": true},
Proxies: []netip.Prefix{netip.MustParsePrefix("10.0.0.0/8")},
PerIP: ratelimit.New(1, 2),
Deadline: time.Second,
}
}
func TestStackEndToEnd(t *testing.T) {
var logs bytes.Buffer
srv := httptest.NewServer(newTestServer(&logs))
defer srv.Close()
// Preflight passes without a token because CORS sits before auth.
pre, _ := http.NewRequest(http.MethodOptions, srv.URL+"/api/orders", nil)
pre.Header.Set("Origin", "https://app.example.test")
pre.Header.Set("Access-Control-Request-Method", "POST")
resp, err := http.DefaultClient.Do(pre)
if err != nil {
t.Fatal(err)
}
resp.Body.Close()
if resp.StatusCode != 204 || resp.Header.Get("Access-Control-Allow-Origin") == "" {
t.Fatalf("preflight: %d %v", resp.StatusCode, resp.Header)
}
req, _ := http.NewRequest("GET", srv.URL+"/api/orders", nil)
req.Header.Set("Authorization", "Bearer t1")
resp, err = http.DefaultClient.Do(req) // Transport adds Accept-Encoding: gzip and decodes
if err != nil {
t.Fatal(err)
}
resp.Body.Close()
if resp.StatusCode != 200 || resp.Header.Get("X-Request-Id") == "" || resp.Header.Get("X-Content-Type-Options") != "nosniff" {
t.Fatalf("GET: %d %v", resp.StatusCode, resp.Header)
}
if !resp.Uncompressed {
t.Fatal("expected a gzip response transparently decoded by the client")
}
// The preflight was answered by CORS, before the limiter. GET used one
// token, the first /healthz uses the second, the next one finds it empty.
for i := 0; i < 2; i++ {
resp, err = http.Get(srv.URL + "/healthz")
if err != nil {
t.Fatal(err)
}
resp.Body.Close()
}
if resp.StatusCode != http.StatusTooManyRequests || resp.Header.Get("Retry-After") == "" {
t.Fatalf("rate limit: %d", resp.StatusCode)
}
if !strings.Contains(logs.String(), "status=429") || !strings.Contains(logs.String(), "status=200") {
t.Fatalf("logs: %s", logs.String())
}
}package after
import (
"bytes"
"net/http"
"net/http/httptest"
"net/netip"
"strings"
"testing"
)
// Round 1, item 7: forwarded addresses must be keyed separately by the
// limiter. If the limiter ran before realip, every request would share one
// key and client B would be limited too.
func TestLimiterKeysOnForwardedClient(t *testing.T) {
var logs bytes.Buffer
d := testDeps(&logs)
d.Proxies = []netip.Prefix{netip.MustParsePrefix("127.0.0.0/8")} // httptest clients come from loopback
srv := httptest.NewServer(NewServer(d))
defer srv.Close()
get := func(xff string) int {
req, _ := http.NewRequest("GET", srv.URL+"/healthz", nil)
req.Header.Set("X-Forwarded-For", xff)
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
resp.Body.Close()
return resp.StatusCode
}
a := []int{get("198.51.100.1"), get("198.51.100.1"), get("198.51.100.1")}
b := get("198.51.100.2")
if a[0] != 200 || a[1] != 200 || a[2] != http.StatusTooManyRequests || b != 200 {
t.Fatalf("client A = %v, client B = %d; want [200 200 429], 200", a, b)
}
}
// Round 1, item 7: a panic below recover is logged by the logging layer
// with status=500, which only holds when logging wraps recover.
func TestPanicIsLoggedWith500(t *testing.T) {
var logs bytes.Buffer
stack := Stack(testDeps(&logs))
h := stack(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { panic("boom") }))
rec := httptest.NewRecorder()
h.ServeHTTP(rec, httptest.NewRequest("GET", "/boom", nil))
out := logs.String()
if rec.Code != 500 || !strings.Contains(out, "panic in handler") || !strings.Contains(out, "status=500") {
t.Fatalf("code=%d logs=%s", rec.Code, out)
}
}The Go angle
Go needs no middleware framework because the standard library already has the two pieces: a one-method Handler interface and closures. A middleware is a function, its dependencies are constructor arguments (Mat Ryer: have "the middleware function take the dependencies, but return a function that takes only the next handler"), the stack is a function call, and the compiler checks the types. What Go does not give you is a context bag on the request object like Laravel's $request->attributes or gin's c.Set: request-scoped data travels in r.Context() under unexported key types, and the response is a write-once stream, so "after" middleware can only observe what was written by wrapping the writer. Those two facts explain most of this page.
The concept catalogue
The middleware shape: func(http.Handler) http.Handler Must-know
In plain words: A middleware takes the next handler and returns a new handler that does something, calls the next one (or not), and maybe does something afterwards. That is the whole trick.
Common misunderstanding: "A middleware is a special framework object." In net/http it is a plain function; http.HandlerFunc turns a closure into a Handler. Another one: "the middleware runs once at startup." The outer function runs once when you build the stack (put expensive setup there); the inner closure runs on every request.
Definition: type Middleware func(next http.Handler) http.Handler. The returned handler must honour the Handler contract: write headers and body to w and return; never touch w or r.Body after returning; do not modify the request except by creating a new one (r.WithContext, r.Clone). A middleware with dependencies is a constructor: func Logging(log *slog.Logger) func(http.Handler) http.Handler.
build time (once) request time (every request)
1 mw := logging.Middleware(log) -
2 h := mw(mux) returns closure -
3 - h.ServeHTTP(w, r): closure runs
4 - before: start := time.Now()
5 - mux.ServeHTTP(rec, r)
6 - after: log status, time.Since(start)Real scenario: a company-wide observability package that every service wraps its mux with; a feature-flag middleware that returns 404 for a route not yet launched; a maintenance-mode switch that answers 503 for everything except /healthz; a per-tenant header check in a B2B API.
| Form | Signature | Used by |
|---|---|---|
| Plain function | func(http.Handler) http.Handler | net/http style, chi, Alice, gorilla/handlers |
| Constructor with deps | func(deps...) func(http.Handler) http.Handler | Mat Ryer's style, this page |
Struct with ServeHTTP | type mw struct{ next http.Handler } | http.TimeoutHandler, httputil.ReverseProxy |
| Framework handler | gin.HandlerFunc = func(*gin.Context) | gin (c.Next(), c.Abort()) |
| Echo | func(echo.HandlerFunc) echo.HandlerFunc | echo |
Fix / how to use it: keep each middleware in its own small package with its own test; take dependencies in the constructor; keep per-request work in the closure.
Chaining and the Chain helper Must-know
In plain words: Chaining is wrapping one middleware inside another. a(b(c(h))) reads inside out, so a Chain(a, b, c) helper lets you list them in the order a request meets them.
Common misunderstanding: "Chain(a, b, c) runs c first because it is closest to the handler." On the way in, a runs first; on the way out, a finishes last. The test below asserts the exact order a> b> c> handler <c <b <a.
Definition: Chain folds the list from the end: h = mws[len-1](final), then each earlier middleware wraps the result. chi's chain does the same ("Wrap the end handler with the middleware chain", looping for i := len(middlewares) - 2; i >= 0; i--). Because Chain returns a Middleware, chains compose: a global chain around the mux, a route-group chain around some handlers.
Chain(a, b, c)(h) == a(b(c(h)))
request ──▶ a> ──▶ b> ──▶ c> ──▶ handler
response ◀── <a ◀── <b ◀── <c ◀──┘
deny inside b: a> ──▶ b writes 401, returns ──▶ <a (c and handler never run)Real scenario: a global chain (ID, logging, recover, headers) around the whole mux plus an api group chain (auth, body limit) around /api/*; an admin group with stricter rate limits; a public /healthz outside the auth group; a webhook group with signature verification instead of auth.
| Approach | Readability | Composition |
|---|---|---|
Nested calls a(b(c(h))) | Inside out; fine for two | Manual |
Reassignment h = c(h); h = b(h); h = a(h) | Reverse order, easy to misread | Manual (Mat Ryer's NewServer uses it) |
Chain(a, b, c)(h) (this page) | Reading order = request order | Chains nest |
chi r.Use(a, b, c) / r.Group / r.With | Reading order | Router-level |
gin r.Use(a, b, c) / group.Use | Reading order | Router-level |
Fix / how to use it:
// Package chain defines the middleware shape and a Chain helper that applies
// middlewares in reading order: the first one listed is the outermost.
package chain
import "net/http"
// Middleware wraps a handler and returns a new one. It can run code before
// and after calling next, or decide not to call next at all.
type Middleware func(next http.Handler) http.Handler
// Chain composes mws so that Chain(a, b, c)(h) == a(b(c(h))).
// a sees the request first and the response last.
func Chain(mws ...Middleware) Middleware {
return func(final http.Handler) http.Handler {
h := final
for i := len(mws) - 1; i >= 0; i-- {
h = mws[i](h)
}
return h
}
}
// Trace is a demo middleware that appends "name>" on the way in and
// "<name" on the way out, so tests can see the onion order.
func Trace(name string, log *[]string) Middleware {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
*log = append(*log, name+">")
next.ServeHTTP(w, r)
*log = append(*log, "<"+name)
})
}
}package chain
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
)
func TestChainOrderIsOnion(t *testing.T) {
var log []string
h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log = append(log, "handler")
})
stack := Chain(Trace("a", &log), Trace("b", &log), Trace("c", &log))(h)
stack.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("GET", "/", nil))
got := strings.Join(log, " ")
want := "a> b> c> handler <c <b <a"
if got != want {
t.Fatalf("order = %q, want %q", got, want)
}
}
func TestShortCircuitSkipsInnerLayers(t *testing.T) {
var log []string
deny := func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Error(w, "no", http.StatusUnauthorized) // next is never called
})
}
h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { log = append(log, "handler") })
rec := httptest.NewRecorder()
Chain(Trace("a", &log), deny, Trace("c", &log))(h).ServeHTTP(rec, httptest.NewRequest("GET", "/", nil))
if rec.Code != 401 || strings.Join(log, " ") != "a> <a" {
t.Fatalf("code=%d log=%v", rec.Code, log)
}
}Ordering: what goes where Must-know
In plain words: A layer can only see what is inside it and can only protect what is inside it. Put each middleware just outside everything it must observe or guard, and just inside everything it depends on.
Common misunderstanding: "Recover should be the outermost." Then the logging middleware inside it never logs the panicked request (the panic unwinds through logging's frame before it can log), and nobody records the 500. Recover goes just inside logging. A second one: "auth first, it is the most important." A CORS preflight carries no cookies or Authorization, so auth before CORS answers every preflight with 401 and the browser blocks the real call.
Definition: the dependency rules behind the standard stack:
| Rule | Consequence |
|---|---|
| Request ID before anything that logs | ID is in the context for every log line |
| Logging outside recover | The 500 written by recover is logged with status |
| Recover outside everything that can panic | Including your own middlewares |
| Real IP before rate limiter, logging of IPs, geo rules | They key on the client, not the load balancer |
| Security headers outside handlers and error paths | Even a 404 or 500 carries nosniff |
| CORS before auth and before the limiter if preflights should not count | Preflights get 204 |
| Rate limiter before expensive work (DB, decompression, JSON) | Rejection costs microseconds |
| Timeout around the handler, not around logging | The log line is written even after a timeout |
| Compression innermost of the body wrappers | Others see uncompressed sizes or must accept compressed ones |
| Metrics close to the handler or outermost, by choice | Inner: handler time; outer: total server time |
wrong: recover(logging(h)) right: logging(recover(h))
1 h panics 1 h panics
2 logging frame unwinds, logs nothing 2 recover catches, writes 500
3 recover writes 500 3 logging sees status=500, logs it
log: (nothing) log: level=ERROR status=500 ...Real scenario: a dashboard showing zero 5xx while users see errors (recover sat outside logging, so panicked requests were never logged); every SPA request failing after "adding auth to everything"; a rate limiter that throttled the whole office because it ran before real IP; compressed sizes in logs that confused capacity planning.
Fix / how to use it: write the stack once in NewServer, comment each line with why it is there (as in After), and keep an end-to-end test that asserts the observable consequences (preflight 204 without a token, 500 logged, 429 with Retry-After).
Request ID Must-know
In plain words: Give every request an identifier, put it in the context so every log line can include it, and echo it in a response header so a user's bug report can be matched to your logs.
Common misunderstanding: "Always trust the inbound X-Request-Id." An attacker can send a megabyte or a log-injection string in it. Accept it only if it is short and well-formed (or only from your own edge), otherwise mint one. Another: "the request ID replaces tracing." It is one string for logs; distributed tracing (W3C traceparent) carries span relationships across services.
Definition: a middleware reads X-Request-Id (or mints 96 random bits with crypto/rand), stores it with context.WithValue under an unexported key type, sets the response header and calls next with r.WithContext(ctx). Readers use an accessor (requestid.From(ctx)), never the key.
1 edge proxy X-Request-Id: 7f3a... (or none)
2 requestid mw valid? keep : mint 24 hex chars; ctx = With(ctx, id); w.Header().Set(...)
3 logging mw request_id=7f3a...
4 handler -> repo log.InfoContext(ctx, ...) via slog handler reading From(ctx)
5 outgoing call req.Header.Set("X-Request-Id", requestid.From(ctx))
6 client sees X-Request-Id in the response, quotes it in the ticketReal scenario: a support ticket with "request id 7f3a..." that leads straight to the failing log lines; correlating a 502 at the load balancer with the backend that produced it; tagging background jobs enqueued by a request; joining access logs and application logs in Loki or Elasticsearch.
| Source | Header | Note |
|---|---|---|
| This page's middleware | X-Request-Id | Accept 1–64 chars [A-Za-z0-9-_], else mint |
chi middleware.RequestID | X-Request-Id | Mints host/random-counter |
| NGINX | $request_id variable | Set it as a header at the edge |
| AWS ALB | X-Amzn-Trace-Id | Added by the load balancer |
| OpenTelemetry | traceparent | Trace and span IDs, not a request ID |
| Laravel | none built in | Usually a custom middleware plus Context::add |
Fix / how to use it:
// Package requestid mints or accepts a request id, stores it in the context
// under an unexported key type and echoes it on the response.
package requestid
import (
"context"
"crypto/rand"
"encoding/hex"
"net/http"
)
// Header is the header read from the edge proxy and echoed to the client.
const Header = "X-Request-Id"
type ctxKey struct{} // unexported: no other package can collide
// From returns the id stored by Middleware, or "".
func From(ctx context.Context) string {
id, _ := ctx.Value(ctxKey{}).(string)
return id
}
// With stores id in ctx (exported for tests and background jobs).
func With(ctx context.Context, id string) context.Context {
return context.WithValue(ctx, ctxKey{}, id)
}
// Middleware accepts a sane inbound id (1..64 chars of [A-Za-z0-9-_]) and
// otherwise mints a random one.
func Middleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
id := r.Header.Get(Header)
if !valid(id) {
var b [12]byte
_, _ = rand.Read(b[:])
id = hex.EncodeToString(b[:])
}
w.Header().Set(Header, id)
next.ServeHTTP(w, r.WithContext(With(r.Context(), id)))
})
}
func valid(s string) bool {
if len(s) == 0 || len(s) > 64 {
return false
}
for _, c := range s {
ok := c == '-' || c == '_' || (c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')
if !ok {
return false
}
}
return true
}package requestid
import (
"net/http"
"net/http/httptest"
"testing"
)
func TestRequestID(t *testing.T) {
var seen string
h := Middleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
seen = From(r.Context())
}))
req := httptest.NewRequest("GET", "/", nil)
req.Header.Set(Header, "abc-123")
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if seen != "abc-123" || rec.Header().Get(Header) != "abc-123" {
t.Fatalf("accepted id: seen=%q echoed=%q", seen, rec.Header().Get(Header))
}
req = httptest.NewRequest("GET", "/", nil)
req.Header.Set(Header, "<script>")
rec = httptest.NewRecorder()
h.ServeHTTP(rec, req)
if seen == "<script>" || len(seen) != 24 {
t.Fatalf("unsafe inbound id must be replaced, got %q", seen)
}
}Logging middleware: slog and status capture Must-know
In plain words: One structured log line per request with method, path, status, bytes, duration and request ID. The status is not visible from outside the handler, so the middleware wraps ResponseWriter with a small recorder that remembers what the handler wrote.
Common misunderstanding: "I can read the status from w after next returns." http.ResponseWriter has no getter; only a wrapper sees WriteHeader. Second: "If the handler never calls WriteHeader, the status is unknown." net/http sends 200 on the first Write, or for an empty body when the handler returns, so the recorder defaults to 200. Third: record the first final WriteHeader. The ResponseWriter doc allows "Any number of 1xx headers ... followed by at most one 2xx-5xx header", so a 103 Early Hints or 100 Continue must be forwarded but not recorded as the status; a second final call is ignored by net/http and logged as http: superfluous response.WriteHeader call from .... (101 Switching Protocols ends the HTTP exchange and counts as final.)
Definition: type StatusRecorder struct { http.ResponseWriter; Status int; Bytes int64 } overrides WriteHeader and Write, and adds Unwrap() http.ResponseWriter so ResponseController can reach the original. The middleware logs with log.LogAttrs(r.Context(), level, "http request", ...), choosing ERROR for 5xx; passing the context lets a slog handler add request-scoped fields (see context: slog). slog itself is covered in CLI Flags, Env & Logging.
1 logging: rec := &StatusRecorder{ResponseWriter: w}; start := now
2 handler: rec.WriteHeader(418) -> rec.Status = 418; forward
3 handler: rec.Write("short and stout") -> rec.Bytes = 15; forward
4 handler returns
5 logging: level=INFO msg="http request" method=GET path=/pot status=418 bytes=15 duration=41µs request_id=r-1
with WriteHeader(103) then WriteHeader(201): both forwarded, Status = 201 (the informational test)Real scenario: an access log that feeds error-rate alerts; latency outliers found by sorting log lines by duration; audit of who called a sensitive endpoint; spotting a client that retries a 429 in a tight loop.
| Field | Source | Pitfall |
|---|---|---|
status | Recorder's first final (non-1xx) WriteHeader, or 200 | 103 recorded as the status; 0 if you forget the 200 rule |
bytes | Sum of Write return values | Compressed or not, depending on position |
duration | time.Since(start) after next returns | Excludes time to flush the last bytes to the socket |
path | r.URL.Path | High cardinality: never a metric label |
request_id | Context accessor | Empty if logging runs before request ID |
| client IP | Real-IP accessor | r.RemoteAddr is the proxy behind a load balancer |
| level | 5xx → ERROR, else INFO | Do not log 4xx as errors |
Fix / how to use it:
// Package logging records one structured slog line per request. It captures
// the status code and body size by wrapping the ResponseWriter, and exposes
// Unwrap so http.ResponseController can still reach Flush, deadlines and
// Hijack on the original writer.
package logging
import (
"log/slog"
"net/http"
"time"
"academy/middlewares/requestid"
)
// StatusRecorder wraps a ResponseWriter and remembers what was written.
type StatusRecorder struct {
http.ResponseWriter
Status int
Bytes int64
}
// Informational reports a 1xx code that is not final: net/http allows any
// number of them (103 Early Hints, 100 Continue) before one 2xx-5xx code.
// 101 Switching Protocols ends the HTTP response, so it counts as final.
func Informational(code int) bool {
return code >= 100 && code <= 199 && code != http.StatusSwitchingProtocols
}
// WriteHeader records the first final status code, as net/http does, and
// forwards 1xx informational codes without treating them as the status.
func (s *StatusRecorder) WriteHeader(code int) {
if s.Status == 0 && !Informational(code) {
s.Status = code
}
s.ResponseWriter.WriteHeader(code)
}
// Write implies 200 when the handler never called WriteHeader.
func (s *StatusRecorder) Write(b []byte) (int, error) {
if s.Status == 0 {
s.Status = http.StatusOK
}
n, err := s.ResponseWriter.Write(b)
s.Bytes += int64(n)
return n, err
}
// Unwrap lets http.NewResponseController find Flush, Hijack,
// SetWriteDeadline and EnableFullDuplex on the wrapped writer (Go 1.20+).
func (s *StatusRecorder) Unwrap() http.ResponseWriter { return s.ResponseWriter }
// Middleware logs method, path, status, bytes, duration and request id.
func Middleware(log *slog.Logger) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
rec := &StatusRecorder{ResponseWriter: w}
next.ServeHTTP(rec, r)
if rec.Status == 0 {
rec.Status = http.StatusOK // handler wrote nothing: net/http sends 200
}
level := slog.LevelInfo
if rec.Status >= 500 {
level = slog.LevelError
}
log.LogAttrs(r.Context(), level, "http request",
slog.String("method", r.Method),
slog.String("path", r.URL.Path),
slog.Int("status", rec.Status),
slog.Int64("bytes", rec.Bytes),
slog.Duration("duration", time.Since(start)),
slog.String("request_id", requestid.From(r.Context())),
)
})
}
}package logging
import (
"bytes"
"log/slog"
"net/http"
"net/http/httptest"
"strings"
"testing"
"academy/middlewares/requestid"
)
func TestLogsStatusBytesAndRequestID(t *testing.T) {
var buf bytes.Buffer
log := slog.New(slog.NewTextHandler(&buf, nil))
h := requestid.Middleware(Middleware(log)(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusTeapot)
_, _ = w.Write([]byte("short and stout"))
})))
req := httptest.NewRequest("GET", "/pot", nil)
req.Header.Set("X-Request-Id", "r-1")
h.ServeHTTP(httptest.NewRecorder(), req)
out := buf.String()
for _, want := range []string{"status=418", "bytes=15", "path=/pot", "request_id=r-1"} {
if !strings.Contains(out, want) {
t.Errorf("log %q lacks %q", out, want)
}
}
}
func TestUnwrapKeepsFlushReachable(t *testing.T) {
log := slog.New(slog.DiscardHandler)
var flushErr error
h := Middleware(log)(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte("chunk"))
flushErr = http.NewResponseController(w).Flush()
}))
rec := httptest.NewRecorder()
h.ServeHTTP(rec, httptest.NewRequest("GET", "/", nil))
if flushErr != nil || !rec.Flushed {
t.Fatalf("flush through wrapper: err=%v flushed=%v", flushErr, rec.Flushed)
}
}
// noUnwrap shows what goes wrong without Unwrap.
type noUnwrap struct{ http.ResponseWriter }
func TestWithoutUnwrapFlushIsNotSupported(t *testing.T) {
rec := httptest.NewRecorder()
err := http.NewResponseController(noUnwrap{rec}).Flush()
if err == nil {
t.Fatal("expected ErrNotSupported without Unwrap")
}
}http.ResponseController and wrapped writers (Unwrap) Must-know
In plain words: Many middlewares wrap the ResponseWriter. If a wrapper hides the original, the handler can no longer flush, hijack for WebSockets or extend its write deadline. http.ResponseController (Go 1.20) solves this by following Unwrap() from wrapper to wrapper until it finds a writer that can do the job.
Common misunderstanding: "Embedding http.ResponseWriter in my struct keeps Flush." Embedding an interface promotes only the interface's methods (Header, Write, WriteHeader); w.(http.Flusher) on your wrapper is false. Either implement Flush, Hijack and friends yourself, or expose Unwrap and call http.NewResponseController(w).Flush().
Definition: NewResponseController(rw) doc: "The ResponseWriter should be the original value passed to the [Handler.ServeHTTP] method, or have an Unwrap method returning the original ResponseWriter." It calls Flush()/FlushError(), Hijack(), SetReadDeadline, SetWriteDeadline and EnableFullDuplex() when found; otherwise it "returns an error matching [ErrNotSupported]". The lookup is a loop: a type switch on rw, and if rw implements Unwrap() ResponseWriter, continue with the result.
handler: http.NewResponseController(w).Flush()
1 w = *gzipWriter has Flush? yes -> gz.Flush(), then controller on inner
2 inner = *StatusRecorder has Flush? no; has Unwrap? yes -> continue
3 inner = *httptest.ResponseRecorder / *http.response has Flush -> bytes go out
without Unwrap at step 2: return error matching http.ErrNotSupportedReal scenario: server-sent events stopping working after someone added a metrics middleware; a WebSocket upgrade failing with "response does not implement http.Hijacker"; a large CSV export cut by Server.WriteTimeout that needs SetWriteDeadline(time.Time{}); gRPC-Web or full-duplex streaming needing EnableFullDuplex.
| Capability | Old way | Go 1.20+ way | What a wrapper must do |
|---|---|---|---|
| Flush | w.(http.Flusher) | rc.Flush() | Unwrap, or Flush that flushes its own buffer first (gzip) |
| Hijack | w.(http.Hijacker) | rc.Hijack() | Unwrap |
| Per-request write deadline | none | rc.SetWriteDeadline(t) | Unwrap |
| Per-request read deadline | none | rc.SetReadDeadline(t) | Unwrap |
| Read body while writing (HTTP/1) | none | rc.EnableFullDuplex() (Go 1.21) | Unwrap |
io.ReaderFrom fast path (sendfile) | w.(io.ReaderFrom) | not covered | Implement ReadFrom or lose it |
Fix / how to use it: every wrapper on this page has Unwrap; the logging tests prove that Flush reaches the recorder through it and that a wrapper without it gets an error. Handlers call http.NewResponseController(w) instead of type assertions.
Recover middleware: panic and http.ErrAbortHandler Must-know
In plain words: If a handler panics, catch it, log it with the stack and the request ID, and answer 500 instead of letting the client see a dropped connection.
Common misunderstanding: "Without recover my server crashes." It does not: net/http already recovers per connection; the doc says the server "recovers the panic, logs a stack trace to the server error log, and either closes the network connection or sends an HTTP/2 RST_STREAM". What you lose without a recover middleware is a proper 500 response, your structured log line and the request ID. And recover does not cover goroutines the handler started: a panic there kills the process. Second: "recover everything." http.ErrAbortHandler is the deliberate way to abort ("panicking with ErrAbortHandler also suppresses logging of a stack trace"); a middleware that swallows it turns an intentional abort into a 500. Re-panic it, as chi's Recoverer does ("we don't recover http.ErrAbortHandler so the response to the client is aborted").
Definition: defer func() { v := recover(); ... }() around next.ServeHTTP. If v == http.ErrAbortHandler, panic(v) again. Otherwise log v and debug.Stack(), and write 500 only if the handler has not started a final response (a 2xx–5xx WriteHeader or body bytes; a 1xx such as 103 does not count) and has not hijacked the connection. Both facts are tracked by a small wrapper: it overrides WriteHeader/Write, and implements Hijack itself (forwarding through ResponseController), so a hijack via w.(http.Hijacker) or via http.NewResponseController(w).Hijack() is recorded, because ResponseController checks the wrapper before following Unwrap. A Connection: Upgrade request header proves nothing: the round-1 test panics on such a request before any hijack and still gets 500. Position: just inside logging (logging wraps recover).
1 logging rec := ...; next.ServeHTTP(rec, r)
2 recover defer installed; next.ServeHTTP(tw, r)
3 handler m["boom"] = 1 -> panic: assignment to entry in nil map
4 recover v != ErrAbortHandler; log ERROR "panic in handler" stack=...; !committed && !hijacked -> 500
5 logging status=500 level=ERROR
handler panics after WriteHeader(202): no second header possible; status stays 202, body truncatedReal scenario: a nil map in a rarely used code path; an index out of range on an empty slice from a new client; a third-party library that panics on malformed input; a reverse proxy (httputil.ReverseProxy) that panics with http.ErrAbortHandler when the client goes away mid-copy.
| Panic | net/http alone | With this middleware |
|---|---|---|
| Ordinary panic, nothing written | Connection closed or RST_STREAM; http: panic serving ADDR: ... in Server.ErrorLog | 500, structured log with stack and request ID |
| Ordinary panic after headers sent | Same | Status unchanged, log with stack |
Panic after only WriteHeader(103) | Same | 500 (103 is not final) |
| Panic after the handler hijacked the connection | Connection already owned by the handler | Log with stack, nothing written |
panic(http.ErrAbortHandler) | Connection aborted, no stack logged | Re-panicked: same as net/http |
| Panic in a goroutine started by the handler | Process crashes | Process crashes (recover in that goroutine) |
log.Fatal/os.Exit in a handler | Process exits | Process exits |
Fix / how to use it:
// Package recoverer turns a panic in a handler into a logged 500 instead of
// a dropped connection, while letting http.ErrAbortHandler through.
package recoverer
import (
"bufio"
"log/slog"
"net"
"net/http"
"runtime/debug"
"academy/middlewares/requestid"
)
// tracker knows whether a final response was started or the connection was
// hijacked; only then must recover not write a 500.
type tracker struct {
http.ResponseWriter
committed bool // a final (non-1xx) status or body bytes were written
hijacked bool
}
func (t *tracker) WriteHeader(code int) {
if !(code >= 100 && code <= 199 && code != http.StatusSwitchingProtocols) {
t.committed = true // 103 Early Hints and friends are not final
}
t.ResponseWriter.WriteHeader(code)
}
func (t *tracker) Write(b []byte) (int, error) {
t.committed = true
return t.ResponseWriter.Write(b)
}
// Hijack is found by w.(http.Hijacker) and by ResponseController, which
// checks the wrapper before following Unwrap; so every hijack is recorded.
func (t *tracker) Hijack() (net.Conn, *bufio.ReadWriter, error) {
c, rw, err := http.NewResponseController(t.ResponseWriter).Hijack()
if err == nil {
t.hijacked = true
}
return c, rw, err
}
func (t *tracker) Unwrap() http.ResponseWriter { return t.ResponseWriter }
// Middleware must sit inside logging and metrics (logging wraps recover), so
// those outer layers observe the 500 this middleware writes.
func Middleware(log *slog.Logger) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
tw := &tracker{ResponseWriter: w}
defer func() {
v := recover()
if v == nil {
return
}
if v == http.ErrAbortHandler {
panic(v) // deliberate abort: let net/http drop the connection quietly
}
log.ErrorContext(r.Context(), "panic in handler",
slog.Any("panic", v),
slog.String("request_id", requestid.From(r.Context())),
slog.String("stack", string(debug.Stack())),
)
if !tw.committed && !tw.hijacked {
http.Error(tw, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
}
}()
next.ServeHTTP(tw, r)
})
}
}package recoverer
import (
"bytes"
"log/slog"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
func TestPanicBecomes500AndIsLogged(t *testing.T) {
var buf bytes.Buffer
h := Middleware(slog.New(slog.NewTextHandler(&buf, nil)))(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var m map[string]int
m["boom"] = 1 // assignment to entry in nil map
}))
rec := httptest.NewRecorder()
h.ServeHTTP(rec, httptest.NewRequest("GET", "/", nil))
if rec.Code != 500 {
t.Fatalf("code = %d", rec.Code)
}
if !strings.Contains(buf.String(), "nil map") {
t.Fatalf("panic not logged: %s", buf.String())
}
}
func TestErrAbortHandlerIsRePanicked(t *testing.T) {
h := Middleware(slog.New(slog.DiscardHandler))(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
panic(http.ErrAbortHandler)
}))
defer func() {
if v := recover(); v != http.ErrAbortHandler {
t.Fatalf("recovered %v, want ErrAbortHandler", v)
}
}()
h.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("GET", "/", nil))
}
func TestPanicAfterHeadersKeepsStatus(t *testing.T) {
h := Middleware(slog.New(slog.DiscardHandler))(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusAccepted)
panic("late")
}))
rec := httptest.NewRecorder()
h.ServeHTTP(rec, httptest.NewRequest("GET", "/", nil))
if rec.Code != http.StatusAccepted {
t.Fatalf("headers already sent, code must stay 202, got %d", rec.Code)
}
}Timeout middleware Important
In plain words: Give each request a time budget by putting a deadline on its context. Handlers that pass the context to the database and HTTP clients stop when the budget is spent.
Common misunderstanding: "A timeout middleware stops the handler." Nothing can stop a goroutine from outside; the handler must watch ctx.Done() (see context: cooperative cancellation). Second: "Use http.TimeoutHandler everywhere." It buffers the whole response and does not support Flusher or Hijacker, so it breaks streaming; it answers 503 with your message and makes later writes fail with http.ErrHandlerTimeout.
Definition: ctx, cancel := context.WithTimeout(r.Context(), d); defer cancel(); next.ServeHTTP(w, r.WithContext(ctx)). The handler maps context.DeadlineExceeded to 504 and context.Canceled (client left) to nothing. http.TimeoutHandler(h, d, msg) is the stdlib alternative that guarantees an answer. Server-level ReadHeaderTimeout, ReadTimeout, WriteTimeout and IdleTimeout on http.Server are a different layer (connection limits, see net/http).
t=0 timeout mw: ctx deadline t+20ms
t=0 handler: select { work 1s | ctx.Done() }
t=20ms ctx.Done(); Err = DeadlineExceeded -> http.Error(w, "request budget exhausted", 504)
with http.TimeoutHandler instead: 503 + msg written by the wrapper; handler writes -> ErrHandlerTimeoutReal scenario: a search endpoint with a 2 s SLO; a report endpoint that must not hold a database connection for minutes; an API gateway that answers 504 itself rather than waiting for a hung backend; protecting a pool from slow-loris style slow handlers.
| Tool | Answers | Streaming | Handler must cooperate |
|---|---|---|---|
| Context timeout middleware (this page) | What the handler writes (504) | Works | Yes |
http.TimeoutHandler | 503 + message, guaranteed | Breaks (Flusher unsupported) | Yes, to stop working |
Server.WriteTimeout | Connection closed, no response | Cuts long streams | No |
ResponseController.SetWriteDeadline | Per-request override | Works | No |
chi middleware.Timeout | Context deadline, then 504 if the handler returns on DeadlineExceeded | Works | Yes |
Fix / how to use it:
// Package timeout gives every request a deadline through its context.
// Unlike http.TimeoutHandler it does not buffer the response, so streaming
// and Flush keep working; the handler must honour ctx.Done().
package timeout
import (
"context"
"errors"
"net/http"
"time"
)
// Middleware derives a context with deadline d from r.Context().
func Middleware(d time.Duration) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), d)
defer cancel()
next.ServeHTTP(w, r.WithContext(ctx))
})
}
}
// Slow is a handler that cooperates: it waits for work or for the deadline.
func Slow(work time.Duration) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
select {
case <-time.After(work):
_, _ = w.Write([]byte("done"))
case <-r.Context().Done():
if errors.Is(r.Context().Err(), context.DeadlineExceeded) {
http.Error(w, "request budget exhausted", http.StatusGatewayTimeout)
}
// context.Canceled: the client left; nothing to write.
}
})
}
// Std wraps h with the standard library's TimeoutHandler: 503 + msg after d,
// later writes by h fail with http.ErrHandlerTimeout.
func Std(h http.Handler, d time.Duration) http.Handler {
return http.TimeoutHandler(h, d, "request budget exhausted")
}package timeout
import (
"net/http/httptest"
"testing"
"time"
)
func TestContextTimeoutGives504(t *testing.T) {
h := Middleware(20 * time.Millisecond)(Slow(time.Second))
rec := httptest.NewRecorder()
start := time.Now()
h.ServeHTTP(rec, httptest.NewRequest("GET", "/", nil))
if rec.Code != 504 || time.Since(start) > 500*time.Millisecond {
t.Fatalf("code=%d after %v", rec.Code, time.Since(start))
}
}
func TestTimeoutHandlerGives503(t *testing.T) {
h := Std(Slow(time.Second), 20*time.Millisecond)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, httptest.NewRequest("GET", "/", nil))
if rec.Code != 503 {
t.Fatalf("code=%d, want 503", rec.Code)
}
}
func TestFastRequestUnaffected(t *testing.T) {
h := Middleware(time.Second)(Slow(time.Millisecond))
rec := httptest.NewRecorder()
h.ServeHTTP(rec, httptest.NewRequest("GET", "/", nil))
if rec.Code != 200 || rec.Body.String() != "done" {
t.Fatalf("code=%d body=%q", rec.Code, rec.Body.String())
}
}Security headers Must-know
In plain words: A handful of response headers tell the browser to be stricter with your content: only load scripts from here, only use HTTPS from now on, do not guess content types, do not let other sites frame this page, send less of the URL to other sites, and switch off camera and geolocation. One middleware sets them on every response.
Common misunderstanding: "Security headers make an API secure." They are browser instructions; curl and attackers' scripts ignore them. They limit the damage of XSS, clickjacking and downgrade attacks in browsers. Second: "Set X-XSS-Protection: 1; mode=block." OWASP warns that this header "can create XSS vulnerabilities in otherwise safe websites", recommends a CSP instead and shows X-XSS-Protection: 0. Third: "HSTS over plain HTTP works." MDN: browsers ignore Strict-Transport-Security received over HTTP, so the snippet sends it only on TLS requests.
Definition: the headers, values and sources (OWASP HTTP Headers Cheat Sheet, MDN):
| Header | Value on this page | What it does | Source note |
|---|---|---|---|
Content-Security-Policy | API: default-src 'none'; frame-ancestors 'none'; HTML: default-src 'self'; script-src 'self'; object-src 'none'; base-uri 'self'; frame-ancestors 'none' | Allowlist of where scripts, styles, frames may come from; frame-ancestors controls who may frame you | OWASP (in its X-XSS-Protection entry): "Use a Content Security Policy (CSP) that disables the use of inline JavaScript" |
Strict-Transport-Security | max-age=63072000; includeSubDomains | Browser uses HTTPS only for two years | OWASP example adds preload; MDN: preload needs max-age ≥ 31536000 and includeSubDomains |
X-Content-Type-Options | nosniff | No MIME sniffing: text/plain is never run as HTML | http.Error already sets it on error responses |
X-Frame-Options | DENY | Legacy anti-clickjacking | OWASP: prefer CSP frame-ancestors; MDN: ALLOW-FROM is obsolete |
Referrer-Policy | API: no-referrer; HTML: strict-origin-when-cross-origin | How much of the URL goes into Referer | MDN: strict-origin-when-cross-origin is the browser default; OWASP: set it explicitly |
Permissions-Policy | geolocation=(), camera=(), microphone=() | Switches browser features off | OWASP's exact example |
Cross-Origin-Opener-Policy | same-origin | Isolates the browsing context | OWASP recommendation |
Cache-Control | no-store (API) | No storage of sensitive responses | OWASP: "Use no-store for sensitive responses" |
X-Powered-By, Server | removed / non-informative | Less fingerprinting | OWASP: remove |
1 secheaders mw: w.Header().Set(...) for each policy entry (before next)
2 handler: w.Header().Set("X-Frame-Options", "SAMEORIGIN") route override still possible
3 handler: WriteHeader(200) headers frozen now
4 browser: honours CSP, nosniff, frame-ancestors; HSTS only if the response came over TLSReal scenario: a stored XSS in a comment field contained by a CSP without 'unsafe-inline'; a login page that cannot be framed by a phishing site; a JSON endpoint returning user text that a browser would otherwise sniff as HTML; a pentest report listing missing headers for every 404 page.
Fix / how to use it: set headers before next (after WriteHeader they are frozen), keep an API preset and an HTML preset, let routes override, and send HSTS only over TLS (or when a trusted proxy says X-Forwarded-Proto: https). For HTML-heavy apps, CSP needs nonces or hashes for inline scripts; start with Content-Security-Policy-Report-Only and a report endpoint.
// Package secheaders sets the response headers OWASP's Secure Headers
// Project recommends. Two presets: one for JSON APIs, one for HTML pages.
package secheaders
import "net/http"
// Policy is a set of headers applied to every response.
type Policy map[string]string
// API is for JSON endpoints that are never rendered as a document.
var API = Policy{
"Content-Security-Policy": "default-src 'none'; frame-ancestors 'none'",
"X-Content-Type-Options": "nosniff",
"X-Frame-Options": "DENY",
"Referrer-Policy": "no-referrer",
"Cache-Control": "no-store",
"Strict-Transport-Security": "max-age=63072000; includeSubDomains",
}
// HTML is for server-rendered pages; tune CSP per application.
var HTML = Policy{
"Content-Security-Policy": "default-src 'self'; script-src 'self'; object-src 'none'; base-uri 'self'; frame-ancestors 'none'",
"X-Content-Type-Options": "nosniff",
"X-Frame-Options": "DENY",
"Referrer-Policy": "strict-origin-when-cross-origin",
"Permissions-Policy": "geolocation=(), camera=(), microphone=()",
"Cross-Origin-Opener-Policy": "same-origin",
"Strict-Transport-Security": "max-age=63072000; includeSubDomains",
}
// Middleware sets p before calling next, so handlers can still override a
// header for one route. HSTS is only sent over HTTPS (r.TLS or a trusted
// X-Forwarded-Proto decided by the caller via isHTTPS).
func Middleware(p Policy, isHTTPS func(*http.Request) bool) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
h := w.Header()
for k, v := range p {
if k == "Strict-Transport-Security" && !isHTTPS(r) {
continue // browsers ignore HSTS over plain HTTP
}
h.Set(k, v)
}
h.Del("X-Powered-By")
next.ServeHTTP(w, r)
})
}
}
// TLSOnly reports HTTPS when the connection itself is TLS.
func TLSOnly(r *http.Request) bool { return r.TLS != nil }package secheaders
import (
"crypto/tls"
"net/http"
"net/http/httptest"
"testing"
)
func TestHeadersSetAndHSTSOnlyOverTLS(t *testing.T) {
h := Middleware(API, TLSOnly)(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}))
rec := httptest.NewRecorder()
h.ServeHTTP(rec, httptest.NewRequest("GET", "http://api.example.test/", nil))
if rec.Header().Get("X-Content-Type-Options") != "nosniff" {
t.Fatal("nosniff missing")
}
if rec.Header().Get("Strict-Transport-Security") != "" {
t.Fatal("HSTS must not be sent over plain HTTP")
}
req := httptest.NewRequest("GET", "https://api.example.test/", nil)
req.TLS = &tls.ConnectionState{}
rec = httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Header().Get("Strict-Transport-Security") == "" {
t.Fatal("HSTS missing over TLS")
}
}
func TestHandlerCanOverride(t *testing.T) {
h := Middleware(HTML, TLSOnly)(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-Frame-Options", "SAMEORIGIN") // this one page is embeddable by us
}))
rec := httptest.NewRecorder()
h.ServeHTTP(rec, httptest.NewRequest("GET", "/", nil))
if rec.Header().Get("X-Frame-Options") != "SAMEORIGIN" {
t.Fatal("route override lost")
}
}CORS: Origin, preflight OPTIONS, Access-Control-Allow-*, credentials, Vary: Origin Must-know
In plain words: A browser does not let a page on https://app.example.test read responses from https://api.example.test unless the API says so with Access-Control-Allow-* headers. For "non-simple" requests (other methods, JSON content type, an Authorization header) the browser first asks with a preflight OPTIONS request.
Common misunderstanding: "Access-Control-Allow-Origin: * plus credentials is fine for an internal API." The browser refuses it: MDN says that for a credentialed request "the server must specify an origin in the value of the Access-Control-Allow-Origin header, instead of specifying the * wildcard". Reflecting any Origin to get around that is the classic CORS hole: every site on the internet can then read your users' data with their cookies. rs/cors removed that behaviour on purpose ("This library has been modified to avoid a well known security issue when configured with AllowedOrigins to * and AllowCredentials to true"). Second: "CORS blocks the request." For simple requests the request reaches the server and has its side effects; CORS only decides whether the script may read the response. Third: forgetting Vary: Origin: when the allowed origin is echoed, MDN says the response "should also include a Vary response header with the value Origin", or a CDN serves origin A's response to origin B.
Definition: the server checks Origin against an allowlist. Preflight (OPTIONS with Access-Control-Request-Method): answer 204 with Access-Control-Allow-Origin: <that origin>, Access-Control-Allow-Methods, Access-Control-Allow-Headers, optional Access-Control-Allow-Credentials: true and Access-Control-Max-Age (MDN: default 5 seconds; browsers cap it), and do not call the handler. Actual request: same Access-Control-Allow-Origin (+ credentials) and optional Access-Control-Expose-Headers. Unknown origin: no CORS headers at all. Vary: Origin on everything. Position: before auth.
1 browser OPTIONS /orders/7 Origin: https://app.example.test Access-Control-Request-Method: DELETE
2 cors mw allowed -> 204 Access-Control-Allow-Origin: https://app.example.test
Access-Control-Allow-Methods: GET, POST, DELETE Max-Age: 600 Vary: Origin
3 browser DELETE /orders/7 Origin + Cookie
4 cors mw sets ACAO + Allow-Credentials, calls auth -> handler
5 browser script may read the 200
evil origin: step 2 has no ACAO -> browser never sends step 3Real scenario: an SPA on a CDN domain calling an API domain; a partner's dashboard embedding your widget API; a page inside a mobile app's web view (still a browser engine: the same CORS rules apply to its page origin), as opposed to the app's native HTTP client, which is not a browser and does not enforce CORS; a public read-only API that can use * because it never uses cookies.
| Need | Hand-written (this page) | rs/cors option | chi | gin | Laravel |
|---|---|---|---|---|---|
| Allowlist | AllowedOrigins map | AllowedOrigins []string (wildcards like http://*.domain.com) | uses go-chi/cors (rs/cors fork) | gin-contrib/cors | config/cors.php allowed_origins |
| Dynamic check | code | AllowOriginVaryRequestFunc | same | AllowOriginFunc | allowed_origins_patterns |
| Credentials | AllowCredentials | AllowCredentials (default false) | same | AllowCredentials | supports_credentials |
| Preflight cache | MaxAge | MaxAge (default 0) | same | MaxAge | max_age |
| Preflight status | 204 | OptionsSuccessStatus (default 204) | same | 204 | HandleCors |
| Let OPTIONS reach handler | no | OptionsPassthrough | same | n/a | n/a |
Fix / how to use it: the hand-written version below is about 50 lines and shows every header; in production rs/cors is the well-tested choice (benchmark in its README: 51 ns/op for Default, 147 ns/op for a preflight). Both are tested against the same cases.
// Package cors shows a small allowlist CORS middleware written by hand and
// the equivalent configuration of github.com/rs/cors.
package cors
import (
"net/http"
"strconv"
"strings"
rscors "github.com/rs/cors"
)
// Config is an explicit allowlist; there is no "*" when credentials are on.
type Config struct {
AllowedOrigins map[string]bool // exact "scheme://host[:port]"
AllowedMethods []string
AllowedHeaders []string
AllowCredentials bool
MaxAge int // seconds the browser may cache a preflight
}
// Middleware answers preflights itself and decorates actual requests.
func Middleware(c Config) func(http.Handler) http.Handler {
methods := strings.Join(c.AllowedMethods, ", ")
headers := strings.Join(c.AllowedHeaders, ", ")
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
h := w.Header()
// The response differs per Origin, so shared caches must key on it.
h.Add("Vary", "Origin")
origin := r.Header.Get("Origin")
preflight := r.Method == http.MethodOptions && r.Header.Get("Access-Control-Request-Method") != ""
if preflight {
h.Add("Vary", "Access-Control-Request-Method")
h.Add("Vary", "Access-Control-Request-Headers")
}
if origin == "" || !c.AllowedOrigins[origin] {
if preflight {
w.WriteHeader(http.StatusNoContent) // no CORS headers: browser blocks
return
}
next.ServeHTTP(w, r) // same-origin or non-browser call, or a denied origin
return
}
h.Set("Access-Control-Allow-Origin", origin) // echo the allowed origin, never "*"
if c.AllowCredentials {
h.Set("Access-Control-Allow-Credentials", "true")
}
if preflight {
h.Set("Access-Control-Allow-Methods", methods)
if headers != "" {
h.Set("Access-Control-Allow-Headers", headers)
}
if c.MaxAge > 0 {
h.Set("Access-Control-Max-Age", strconv.Itoa(c.MaxAge))
}
w.WriteHeader(http.StatusNoContent)
return
}
next.ServeHTTP(w, r)
})
}
}
// RS builds the same policy with rs/cors.
func RS(origins []string) func(http.Handler) http.Handler {
c := rscors.New(rscors.Options{
AllowedOrigins: origins,
AllowedMethods: []string{http.MethodGet, http.MethodPost, http.MethodPut, http.MethodDelete},
AllowedHeaders: []string{"Authorization", "Content-Type"},
AllowCredentials: true,
MaxAge: 600,
})
return c.Handler
}package cors
import (
"net/http"
"net/http/httptest"
"testing"
)
var cfg = Config{
AllowedOrigins: map[string]bool{"https://app.example.test": true},
AllowedMethods: []string{"GET", "POST", "DELETE"},
AllowedHeaders: []string{"Authorization", "Content-Type"},
AllowCredentials: true,
MaxAge: 600,
}
func ok() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { _, _ = w.Write([]byte("ok")) })
}
func preflight(origin string) *http.Request {
r := httptest.NewRequest(http.MethodOptions, "/orders/7", nil)
r.Header.Set("Origin", origin)
r.Header.Set("Access-Control-Request-Method", "DELETE")
r.Header.Set("Access-Control-Request-Headers", "authorization")
return r
}
func TestPreflightAllowed(t *testing.T) {
for name, mw := range map[string]func(http.Handler) http.Handler{
"hand": Middleware(cfg), "rs/cors": RS([]string{"https://app.example.test"}),
} {
rec := httptest.NewRecorder()
mw(ok()).ServeHTTP(rec, preflight("https://app.example.test"))
h := rec.Header()
if rec.Code != 204 || h.Get("Access-Control-Allow-Origin") != "https://app.example.test" ||
h.Get("Access-Control-Allow-Credentials") != "true" || h.Values("Vary") == nil {
t.Errorf("%s: code=%d headers=%v", name, rec.Code, h)
}
}
}
func TestUnknownOriginGetsNoCORSHeaders(t *testing.T) {
for name, mw := range map[string]func(http.Handler) http.Handler{
"hand": Middleware(cfg), "rs/cors": RS([]string{"https://app.example.test"}),
} {
rec := httptest.NewRecorder()
mw(ok()).ServeHTTP(rec, preflight("https://evil.example.test"))
if v := rec.Header().Get("Access-Control-Allow-Origin"); v != "" {
t.Errorf("%s: leaked ACAO %q", name, v)
}
}
}
func TestActualRequestEchoesOriginAndVaries(t *testing.T) {
r := httptest.NewRequest("GET", "/orders", nil)
r.Header.Set("Origin", "https://app.example.test")
rec := httptest.NewRecorder()
Middleware(cfg)(ok()).ServeHTTP(rec, r)
if rec.Body.String() != "ok" || rec.Header().Get("Vary") != "Origin" ||
rec.Header().Get("Access-Control-Allow-Origin") != "https://app.example.test" {
t.Fatalf("headers=%v body=%q", rec.Header(), rec.Body.String())
}
}Compression: gzip, Accept-Encoding, Content-Encoding, Vary, BREACH note, Content-Length removal Important
In plain words: If the client says Accept-Encoding: gzip, compress the body on the fly, say so with Content-Encoding: gzip, tell caches that the answer depends on Accept-Encoding, and drop the Content-Length the handler may have set, because it describes the uncompressed body.
Common misunderstanding: "Compression is always a win." Small bodies (a few hundred bytes) and already compressed content (JPEG, MP4, zip, a Content-Encoding: br file) only cost CPU. Second: "A wrong Content-Length is harmless." The client waits for bytes that never come, or net/http fails with http: wrote more than the declared Content-Length. Third: "gzip over TLS is safe." BREACH attacks HTTP-level compression of responses that "Reflect a secret (such as a CSRF token) in HTTP response bodies" together with attacker-controlled input; it "can be exploited with just a few thousand requests". Mitigations: do not compress responses that mix secrets and user input, mask tokens per request, or add length randomisation (klauspost gzhttp offers RandomJitter, its "Heal the Breach" option).
Definition: the middleware always adds Vary: Accept-Encoding, parses the q weight numerically (RFC 9110: qvalue = ( "0" [ "." 0*3DIGIT ] ) / ... and "a value of 0 means "not acceptable"", so gzip;q=0, q=0.0 and q=0.000 all disable gzip), skips HEAD, and wraps w. The wrapper forwards 1xx codes at once but holds back the final status until the body starts; it then commits exactly once, on the first Write, the first Flush, or when the handler returns: it sniffs Content-Type from the first uncompressed bytes if unset (also after an explicit WriteHeader(201)), sets Content-Encoding: gzip, deletes Content-Length, skips 204/304, bodiless responses and responses that already have Content-Encoding, and on return calls gz.Close() to write the gzip footer. Committing on Flush matters: the underlying writer's Flush sends a 200 header block, so a Flush before the first Write must decide the encoding first, or gzip bytes would follow headers without Content-Encoding. Writers come from a sync.Pool (gzip.NewWriterLevel(..., gzip.BestSpeed)), because each gzip writer allocates large internal compression buffers and allocating one per request shows up in GC profiles. Flush must flush the gzip writer first, then the underlying writer. On the client side, Go's http.Transport requests gzip itself "when the Request contains no existing Accept-Encoding value" and, if it gets a gzipped response, decodes it transparently (resp.Uncompressed is then true, which the end-to-end test asserts); DisableCompression: true turns that off.
1 client GET /orders Accept-Encoding: br, gzip
2 compress Vary: Accept-Encoding; gw := pooled gzip writer
3 handler Header: Content-Type: application/json, Content-Length: 5000; Write(5000 bytes)
4 gw first Write: sniff Content-Type if unset; Content-Encoding: gzip; Del(Content-Length); WriteHeader(200); gz.Write
Flush before any Write: same commit (gzip headers) before the underlying Flush
5 compress gz.Close() -> footer; Reset; pool.Put
6 wire 77 bytes (real test: identity 5000 bytes -> gzip 77 bytes), chunkedReal scenario: JSON list endpoints shrinking 10× or more; a CDN caching the gzip variant and serving it to a client that did not ask for it (missing Vary); an SSE stream stuck in the gzip buffer (missing Flush); a CSRF token in a page that also reflects a search query (BREACH).
| Option | Encodings | Notes |
|---|---|---|
| This page's middleware | gzip | Shows every rule; stdlib only |
chi middleware.Compress(level, types...) | gzip, deflate (+ custom encoders) | Compresses listed content types only; sets Vary, deletes Content-Length |
github.com/klauspost/compress/gzhttp | gzip (+ zstd) | Minimum size, content-type filters, BREACH jitter |
| Reverse proxy or CDN | gzip, br, zstd (per product) | Often the better place: frees app CPU |
| Pre-compressed static files | br, gzip | Serve .br/.gz with Content-Encoding set; middleware must skip them |
Fix / how to use it: compress at one layer only (edge or app, not both), restrict to text types above a minimum size, and keep pages that carry secrets uncompressed or tokens masked. Algorithms themselves are in Compression.
// Package compress gzips responses for clients that send
// Accept-Encoding: gzip. It sets Content-Encoding and Vary, drops
// Content-Length (the compressed size is unknown up front), skips bodies
// that are already encoded, and reuses writers from a sync.Pool.
//
// The final status is held back until the first body bytes (or a Flush, or
// the end of the handler), so Content-Type can be sniffed from uncompressed
// bytes and the encoding decision is made exactly once.
package compress
import (
"compress/gzip"
"io"
"net/http"
"strconv"
"strings"
"sync"
)
var pool = sync.Pool{New: func() any {
w, _ := gzip.NewWriterLevel(io.Discard, gzip.BestSpeed)
return w
}}
type gzipWriter struct {
http.ResponseWriter
gz *gzip.Writer
code int // final status requested by the handler, not yet sent
committed bool // final status sent to the underlying writer
skip bool // pass the body through untouched
}
func informational(code int) bool {
return code >= 100 && code <= 199 && code != http.StatusSwitchingProtocols
}
// WriteHeader forwards 1xx codes at once (103 Early Hints, 100 Continue)
// and remembers the first final code until the body starts.
func (g *gzipWriter) WriteHeader(code int) {
if informational(code) {
g.ResponseWriter.WriteHeader(code)
return
}
if g.code == 0 && !g.committed {
g.code = code
}
}
// commit decides on the encoding and sends the final status. first are the
// first body bytes (nil for Flush or an empty body).
func (g *gzipWriter) commit(first []byte, hasBody bool) {
if g.committed {
return
}
g.committed = true
if g.code == 0 {
g.code = http.StatusOK
}
h := g.Header()
if len(first) > 0 && h.Get("Content-Type") == "" {
h.Set("Content-Type", http.DetectContentType(first)) // sniff before gzip
}
// Already encoded (an upstream proxy, a pre-gzipped file) or no body.
if !hasBody || h.Get("Content-Encoding") != "" || g.code == http.StatusNoContent || g.code == http.StatusNotModified {
g.skip = true
} else {
h.Set("Content-Encoding", "gzip")
h.Del("Content-Length") // would describe the uncompressed body
g.gz.Reset(g.ResponseWriter)
}
g.ResponseWriter.WriteHeader(g.code)
}
func (g *gzipWriter) Write(b []byte) (int, error) {
g.commit(b, true)
if g.skip {
return g.ResponseWriter.Write(b)
}
return g.gz.Write(b)
}
// Flush commits the gzip headers first if nothing was written yet, so no
// gzip bytes can ever follow an unencoded header block (SSE, streaming JSON).
func (g *gzipWriter) Flush() {
g.commit(nil, true)
if !g.skip {
_ = g.gz.Flush()
}
_ = http.NewResponseController(g.ResponseWriter).Flush()
}
func (g *gzipWriter) Unwrap() http.ResponseWriter { return g.ResponseWriter }
// Middleware compresses when the client accepts gzip.
func Middleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// The representation depends on Accept-Encoding for every response.
w.Header().Add("Vary", "Accept-Encoding")
if !acceptsGzip(r.Header.Get("Accept-Encoding")) || r.Method == http.MethodHead {
next.ServeHTTP(w, r)
return
}
gz := pool.Get().(*gzip.Writer)
gw := &gzipWriter{ResponseWriter: w, gz: gz}
defer func() {
if gw.code != 0 {
gw.commit(nil, false) // WriteHeader without a body: send it uncompressed
}
if gw.committed && !gw.skip {
_ = gz.Close() // writes the gzip footer
}
gz.Reset(io.Discard)
pool.Put(gz)
}()
next.ServeHTTP(gw, r)
})
}
// acceptsGzip reports whether gzip is listed with a non-zero qvalue.
// RFC 9110: qvalue = "0" [ "." 0*3DIGIT ] / "1" [ "." 0*3("0") ], and a
// value of 0 (also written 0.0, 0.00, 0.000) means "not acceptable".
func acceptsGzip(h string) bool {
for _, part := range strings.Split(h, ",") {
name, params, _ := strings.Cut(strings.TrimSpace(part), ";")
if !strings.EqualFold(strings.TrimSpace(name), "gzip") {
continue
}
q := 1.0
for _, p := range strings.Split(params, ";") {
k, v, ok := strings.Cut(strings.TrimSpace(p), "=")
if ok && strings.EqualFold(strings.TrimSpace(k), "q") {
f, err := strconv.ParseFloat(strings.TrimSpace(v), 64)
if err != nil || f < 0 || f > 1 {
return false // malformed weight: do not guess
}
q = f
}
}
return q > 0
}
return false
}package compress
import (
"compress/gzip"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
var body = strings.Repeat(`{"id":1,"name":"widget"},`, 200)
func handler() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Content-Length", "5000") // set before the middleware knows
_, _ = io.WriteString(w, body)
})
}
func TestGzipWhenAccepted(t *testing.T) {
req := httptest.NewRequest("GET", "/", nil)
req.Header.Set("Accept-Encoding", "br, gzip")
rec := httptest.NewRecorder()
Middleware(handler()).ServeHTTP(rec, req)
if rec.Header().Get("Content-Encoding") != "gzip" || rec.Header().Get("Content-Length") != "" {
t.Fatalf("headers = %v", rec.Header())
}
if rec.Header().Get("Vary") != "Accept-Encoding" {
t.Fatalf("Vary = %q", rec.Header().Get("Vary"))
}
compressed := rec.Body.Len()
if compressed >= len(body) {
t.Fatalf("not smaller: %d >= %d", rec.Body.Len(), len(body))
}
zr, err := gzip.NewReader(rec.Body)
if err != nil {
t.Fatal(err)
}
got, _ := io.ReadAll(zr)
if string(got) != body {
t.Fatal("round trip mismatch")
}
t.Logf("identity %d bytes -> gzip %d bytes", len(body), compressed)
}
func TestIdentityWhenNotAccepted(t *testing.T) {
for _, ae := range []string{"", "br", "gzip;q=0"} {
req := httptest.NewRequest("GET", "/", nil)
req.Header.Set("Accept-Encoding", ae)
rec := httptest.NewRecorder()
Middleware(handler()).ServeHTTP(rec, req)
if rec.Header().Get("Content-Encoding") != "" || rec.Body.String() != body {
t.Errorf("Accept-Encoding %q: compressed anyway", ae)
}
}
}
func TestAlreadyEncodedPassesThrough(t *testing.T) {
h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Encoding", "br")
_, _ = w.Write([]byte("pre-compressed"))
})
req := httptest.NewRequest("GET", "/", nil)
req.Header.Set("Accept-Encoding", "gzip")
rec := httptest.NewRecorder()
Middleware(h).ServeHTTP(rec, req)
if rec.Header().Get("Content-Encoding") != "br" || rec.Body.String() != "pre-compressed" {
t.Fatal("double compression")
}
}Real IP and X-Forwarded-For trust Must-know
In plain words: Behind a load balancer, r.RemoteAddr is the load balancer. The client IP is in X-Forwarded-For, but anybody can send that header, so you may trust only the parts added by proxies you run.
Common misunderstanding: "Take the first (leftmost) address of X-Forwarded-For." That one is written by the client. MDN: "Any security-related use of X-Forwarded-For (such as for rate limiting or IP-based access control) must only use IP addresses added by a trusted proxy" and "Using untrustworthy values can result in rate-limiter avoidance, access-control bypass, memory exhaustion". chi deprecated its RealIP middleware for exactly this ("RealIP is vulnerable to IP spoofing — it mutates r.RemoteAddr to the leftmost X-Forwarded-For value") in favour of ClientIPFromXFF, which walks "the chain right-to-left and skipping any IP that falls within one of the given trusted CIDR prefixes".
Definition: if the TCP peer is not a trusted proxy, it is the client and the header is ignored. Otherwise walk X-Forwarded-For right to left, skip trusted hops, and the first untrusted address is the client; a garbage entry fails closed. Normalise v4-mapped IPv6 (netip.Addr.Unmap). Store the result in the context; do not overwrite r.RemoteAddr. RFC 7239 standardised Forwarded: for=... with the same trust problem.
client 198.51.100.7 sends X-Forwarded-For: 1.2.3.4 (spoofed)
LB 10.0.0.5 appends X-Forwarded-For: 1.2.3.4, 198.51.100.7
app sees RemoteAddr 10.0.0.5 (trusted) -> walk right to left:
1 198.51.100.7 not trusted -> client = 198.51.100.7
leftmost rule would have said 1.2.3.4: attacker picks a fresh IP per requestReal scenario: a per-IP login rate limit bypassed by rotating the header; an admin allowlist by IP fooled by X-Forwarded-For: 127.0.0.1; geo-blocking by a spoofed address; logs showing only the load balancer's IP.
| Setup | What to trust | Config |
|---|---|---|
| No proxy | RemoteAddr only | no header |
| One NGINX on the same host | XFF from 127.0.0.1 | trusted 127.0.0.1/32 |
| Cloud LB + app | LB subnet CIDRs | trusted VPC range |
| CDN (Cloudflare) | CF-Connecting-IP only from CDN ranges | chi ClientIPFromHeader("CF-Connecting-IP", ranges...) |
| Laravel | TrustProxies middleware with at: proxies | $middleware->trustProxies(at: [...]) |
| NGINX itself | set_real_ip_from + real_ip_recursive on | same right-to-left idea |
Fix / how to use it:
// Package realip finds the client IP behind reverse proxies. It trusts
// X-Forwarded-For only when the TCP peer is a known proxy, and walks the
// list right to left, skipping trusted hops: the first untrusted address is
// the client. The leftmost entry is whatever the client chose to send.
package realip
import (
"context"
"net"
"net/http"
"net/netip"
"strings"
)
type ctxKey struct{}
// From returns the client IP stored by Middleware.
func From(ctx context.Context) (netip.Addr, bool) {
a, ok := ctx.Value(ctxKey{}).(netip.Addr)
return a, ok
}
// Middleware stores the client IP in the context. trusted are the CIDRs of
// your own load balancers / CDN edges.
func Middleware(trusted ...netip.Prefix) func(http.Handler) http.Handler {
isTrusted := func(a netip.Addr) bool {
for _, p := range trusted {
if p.Contains(a) {
return true
}
}
return false
}
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if ip, ok := ClientIP(r, isTrusted); ok {
r = r.WithContext(context.WithValue(r.Context(), ctxKey{}, ip))
}
next.ServeHTTP(w, r)
})
}
}
// ClientIP applies the right-to-left rule; it never mutates r.RemoteAddr.
func ClientIP(r *http.Request, isTrusted func(netip.Addr) bool) (netip.Addr, bool) {
host, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
return netip.Addr{}, false
}
peer, err := netip.ParseAddr(host)
if err != nil {
return netip.Addr{}, false
}
peer = peer.Unmap()
if !isTrusted(peer) {
return peer, true // direct client: ignore any header it sent
}
var hops []string
for _, v := range r.Header.Values("X-Forwarded-For") {
hops = append(hops, strings.Split(v, ",")...)
}
for i := len(hops) - 1; i >= 0; i-- {
a, err := netip.ParseAddr(strings.TrimSpace(hops[i]))
if err != nil {
return netip.Addr{}, false // garbage mid-chain: fail closed
}
a = a.Unmap()
if !isTrusted(a) {
return a, true
}
}
return peer, true // every hop was ours
}package realip
import (
"net/http"
"net/http/httptest"
"net/netip"
"testing"
)
var lb = netip.MustParsePrefix("10.0.0.0/8")
func clientOf(remote, xff string) string {
var got string
h := Middleware(lb)(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if a, ok := From(r.Context()); ok {
got = a.String()
}
}))
r := httptest.NewRequest("GET", "/", nil)
r.RemoteAddr = remote
if xff != "" {
r.Header.Set("X-Forwarded-For", xff)
}
h.ServeHTTP(httptest.NewRecorder(), r)
return got
}
func TestRealIP(t *testing.T) {
cases := []struct{ name, remote, xff, want string }{
{"direct client ignores header", "203.0.113.9:5000", "1.2.3.4", "203.0.113.9"},
{"behind our LB", "10.0.0.5:443", "198.51.100.7", "198.51.100.7"},
{"spoofed leftmost is skipped", "10.0.0.5:443", "1.2.3.4, 198.51.100.7", "198.51.100.7"},
{"two of our hops", "10.0.0.5:443", "198.51.100.7, 10.1.2.3", "198.51.100.7"},
{"garbage fails closed", "10.0.0.5:443", "198.51.100.7, nonsense", ""},
}
for _, c := range cases {
if got := clientOf(c.remote, c.xff); got != c.want {
t.Errorf("%s: got %q want %q", c.name, got, c.want)
}
}
}Rate limiter middleware: x/time/rate per client, token bucket, 429, Retry-After Must-know
In plain words: Each client gets a bucket of tokens that refills at a steady rate. A request takes a token; with no token left it gets 429 Too Many Requests and a Retry-After header saying when to try again.
Common misunderstanding: "One global rate.Limiter is a rate limiter middleware." It throttles everybody together: one noisy client blocks all. You need one bucket per key, and a way to forget idle keys or the map grows without bound. Second: "Use lim.Wait(ctx) in middleware." Waiting holds a goroutine and a connection per excess request, which is what you were trying to avoid; reject with 429 instead. Third: in-process limits multiply with replicas: 10 pods × 5 req/s is 50 req/s per client.
Definition: rate.NewLimiter(r, b) "implements a "token bucket" of size b, initially full and refilled at r tokens per second"; "If no token is available, Allow returns false". The middleware keeps map[string]*entry{lim, lastSeen} under a mutex, sweeps entries idle for 10 minutes, and for each request calls ReserveN(now, 1): zero delay means go on; a positive delay means CancelAt(now) (return the token) and answer 429 with Retry-After: ceil(delay). The key is the authenticated user or API key when known, else the client IP from Real IP. Algorithms (fixed window, sliding window, leaky bucket) and x/time/rate internals are in Rate Limiting in Go; distributed limits in Rate Limiting algorithms.
r = 0.5/s, burst 3, client alice (test with a fake clock)
t=0s req1 req2 req3 tokens 3 -> 0 200 200 200
t=0s req4 delay 2s 429 Retry-After: 2
t=0s bob req1 own bucket 200
t=2s alice req5 1 token refilled 200Real scenario: a login endpoint limited to 5 attempts per minute per account and per IP; a public API with per-key quotas; protecting an expensive search from a scraper; stopping a buggy client that retries in a loop.
| Layer | Scope | Cost of rejection | When |
|---|---|---|---|
This middleware (x/time/rate map) | One process | ~1 µs | Single instance, or per-instance protection |
Redis (INCR + EXPIRE, or a Lua token bucket) | All replicas | One round trip | Real per-client quotas across pods |
API gateway / ingress (for example NGINX limit_req) | Edge | Before your process | First line of defence |
chi middleware.Throttle(n) | Concurrency, not rate | Queue or 429 | Cap in-flight requests |
Laravel throttle:api / RateLimiter::for | Cache store (Redis) | One cache call | Laravel apps; 429 automatically |
Fix / how to use it:
// Package ratelimit keeps one golang.org/x/time/rate token bucket per client
// key and answers 429 Too Many Requests with Retry-After when it is empty.
// State lives in one process; see the chapter for distributed limits.
package ratelimit
import (
"math"
"net/http"
"strconv"
"sync"
"time"
"golang.org/x/time/rate"
)
type entry struct {
lim *rate.Limiter
seen time.Time
}
// Limiter maps a client key to its bucket and forgets idle clients.
type Limiter struct {
mu sync.Mutex
clients map[string]*entry
r rate.Limit
burst int
idle time.Duration
lastGC time.Time
now func() time.Time
}
// New allows r events per second with bursts of b per client.
func New(r rate.Limit, b int) *Limiter {
return &Limiter{clients: map[string]*entry{}, r: r, burst: b, idle: 10 * time.Minute, now: time.Now}
}
func (l *Limiter) get(key string) *rate.Limiter {
l.mu.Lock()
defer l.mu.Unlock()
now := l.now()
if now.Sub(l.lastGC) > time.Minute { // amortised sweep, no extra goroutine
for k, e := range l.clients {
if now.Sub(e.seen) > l.idle {
delete(l.clients, k)
}
}
l.lastGC = now
}
e, ok := l.clients[key]
if !ok {
e = &entry{lim: rate.NewLimiter(l.r, l.burst)}
l.clients[key] = e
}
e.seen = now
return e.lim
}
// Len reports how many clients are tracked (for tests and a gauge).
func (l *Limiter) Len() int { l.mu.Lock(); defer l.mu.Unlock(); return len(l.clients) }
// Middleware limits by key(r): the authenticated user, an API key, or the
// client IP from a trusted real-IP middleware. Never the raw header.
func (l *Limiter) Middleware(key func(*http.Request) string) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
lim := l.get(key(r))
res := lim.ReserveN(l.now(), 1)
if d := res.DelayFrom(l.now()); d > 0 || !res.OK() {
res.CancelAt(l.now()) // give the token back: we are not waiting
secs := int(math.Ceil(d.Seconds()))
if secs < 1 {
secs = 1
}
w.Header().Set("Retry-After", strconv.Itoa(secs))
http.Error(w, "rate limit exceeded", http.StatusTooManyRequests)
return
}
next.ServeHTTP(w, r)
})
}
}package ratelimit
import (
"net/http"
"net/http/httptest"
"testing"
"time"
)
func TestBurstThen429WithRetryAfter(t *testing.T) {
now := time.Unix(1_700_000_000, 0)
l := New(0.5, 3) // one token every 2 s, bucket of 3
l.now = func() time.Time { return now }
h := l.Middleware(func(r *http.Request) string { return r.Header.Get("X-Test-Client") })(
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}))
call := func(client string) *httptest.ResponseRecorder {
r := httptest.NewRequest("GET", "/", nil)
r.Header.Set("X-Test-Client", client)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, r)
return rec
}
for i := 0; i < 3; i++ {
if c := call("alice").Code; c != 200 {
t.Fatalf("burst request %d: %d", i, c)
}
}
rec := call("alice")
if rec.Code != http.StatusTooManyRequests || rec.Header().Get("Retry-After") != "2" {
t.Fatalf("4th: code=%d Retry-After=%q", rec.Code, rec.Header().Get("Retry-After"))
}
if c := call("bob").Code; c != 200 {
t.Fatalf("bob has his own bucket, got %d", c)
}
now = now.Add(2 * time.Second) // one token refilled
if c := call("alice").Code; c != 200 {
t.Fatalf("after refill: %d", c)
}
}
func TestIdleClientsAreForgotten(t *testing.T) {
now := time.Unix(1_700_000_000, 0)
l := New(10, 10)
l.now = func() time.Time { return now }
l.get("a")
l.get("b")
now = now.Add(11 * time.Minute)
l.get("c")
if n := l.Len(); n != 1 {
t.Fatalf("tracked %d clients, want 1", n)
}
}Response time / metrics middleware (Prometheus histogram) Important
In plain words: Measure how long each request took and record it in a histogram labelled by route, method and status code, so you can graph p50/p99 latency and error rates per endpoint.
Common misunderstanding: "Label by r.URL.Path." /orders/1, /orders/2, ... create one time series each and can take Prometheus down; label by the route pattern (GET /orders/{id}), which Go 1.23 also exposes as r.Pattern inside the mux. Second: "Average latency is enough." Averages hide the tail; histograms let you compute quantiles across instances. Third: "promhttp records panics." Its doc says "If the wrapped Handler panics, no values are reported", so put recover inside metrics if you want 500s counted.
Definition: prometheus.NewHistogramVec(HistogramOpts{Name: "http_request_duration_seconds", Buckets: prometheus.DefBuckets}, []string{"route", "method", "code"}) with DefBuckets = []float64{.005, .01, .025, .05, .1, .25, .5, 1, 2.5, 5, 10}. The middleware wraps w to capture the code, times next, and calls Observe(seconds). promhttp.InstrumentHandlerDuration(obs, next) is the library version: it allows only the labels code and method ("The function panics otherwise"), so curry the route in with MustCurryWith. Expose with promhttp.Handler() on /metrics. Tracing and dashboards are in Observability.
1 metrics mw start := now; cw := &codeWriter{w}
2 handler http.NotFound -> cw.code = 404
3 metrics mw Duration.WithLabelValues("GET /orders/{id}", "GET", "404").Observe(0.00004)
4 scrape http_request_duration_seconds_bucket{route="GET /orders/{id}",code="404",le="0.005"} 3
5 PromQL histogram_quantile(0.99, sum by (le, route) (rate(..._bucket[5m])))Real scenario: an SLO alert on p99 of POST /checkout; a capacity graph by route; spotting that 5xx come from one endpoint; comparing latency before and after a deploy.
| Choice | Example | Effect |
|---|---|---|
| Label route pattern | GET /orders/{id} | Bounded series (the test asserts 3 paths → 1 series) |
| Label raw path | /orders/123 | Unbounded cardinality |
DefBuckets | 5 ms … 10 s | Fine for most APIs |
| Custom buckets | .001 … 1 | Fast internal services |
| Native histograms | NativeHistogramBucketFactor | Fewer series, needs Prometheus with native histograms enabled |
Server-Timing header | app;dur=12.3 | Visible in browser dev tools; must be set before the headers are sent, so a duration middleware cannot write it (not done in the snippet) |
Fix / how to use it:
// Package metrics measures response time per route with a Prometheus
// histogram, both by hand and with promhttp.InstrumentHandlerDuration.
package metrics
import (
"net/http"
"strconv"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
// Duration is labelled by route pattern, method and status code. Never
// label by raw URL path: /orders/1, /orders/2 ... explode cardinality.
var Duration = prometheus.NewHistogramVec(prometheus.HistogramOpts{
Name: "http_request_duration_seconds",
Help: "Time from first middleware to handler return.",
Buckets: prometheus.DefBuckets, // .005 ... 10 s
}, []string{"route", "method", "code"})
type codeWriter struct {
http.ResponseWriter
code int
}
func (c *codeWriter) WriteHeader(code int) {
// 1xx informational codes (103 Early Hints) are not the final status.
informational := code >= 100 && code <= 199 && code != http.StatusSwitchingProtocols
if c.code == 0 && !informational {
c.code = code
}
c.ResponseWriter.WriteHeader(code)
}
func (c *codeWriter) Write(b []byte) (int, error) {
if c.code == 0 {
c.code = http.StatusOK
}
return c.ResponseWriter.Write(b)
}
func (c *codeWriter) Unwrap() http.ResponseWriter { return c.ResponseWriter }
// Middleware observes the duration under a fixed route label. It does not
// write Server-Timing: the duration is only known after the headers are sent.
func Middleware(route string, h *prometheus.HistogramVec) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
cw := &codeWriter{ResponseWriter: w}
next.ServeHTTP(cw, r)
if cw.code == 0 {
cw.code = http.StatusOK
}
h.WithLabelValues(route, r.Method, strconv.Itoa(cw.code)).Observe(time.Since(start).Seconds())
})
}
}
// Promhttp is the library version: labels "code" and "method" only, the
// route is curried in as a constant label.
func Promhttp(route string, h *prometheus.HistogramVec, next http.Handler) http.Handler {
return promhttp.InstrumentHandlerDuration(h.MustCurryWith(prometheus.Labels{"route": route}), next)
}package metrics
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/prometheus/client_golang/prometheus"
)
func count(t *testing.T, reg *prometheus.Registry) uint64 {
t.Helper()
mfs, err := reg.Gather()
if err != nil {
t.Fatal(err)
}
var n uint64
for _, mf := range mfs {
for _, m := range mf.GetMetric() {
n += m.GetHistogram().GetSampleCount()
}
}
return n
}
func TestHistogramObservesEachRequest(t *testing.T) {
reg := prometheus.NewRegistry()
h := prometheus.NewHistogramVec(prometheus.HistogramOpts{Name: "d", Buckets: prometheus.DefBuckets},
[]string{"route", "method", "code"})
reg.MustRegister(h)
notFound := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { http.NotFound(w, r) })
mw := Middleware("GET /orders/{id}", h)(notFound)
for _, p := range []string{"/orders/1", "/orders/2", "/orders/3"} {
mw.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("GET", p, nil))
}
if n := count(t, reg); n != 3 {
t.Fatalf("samples = %d", n)
}
// Three different paths, one series: the route label keeps cardinality at 1.
mfs, _ := reg.Gather()
if len(mfs[0].GetMetric()) != 1 {
t.Fatalf("series = %d, want 1", len(mfs[0].GetMetric()))
}
ph := prometheus.NewHistogramVec(prometheus.HistogramOpts{Name: "p"}, []string{"route", "code", "method"})
reg2 := prometheus.NewRegistry()
reg2.MustRegister(ph)
Promhttp("GET /orders/{id}", ph, notFound).ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("GET", "/orders/9", nil))
if n := count(t, reg2); n != 1 {
t.Fatalf("promhttp samples = %d", n)
}
}Request body size limit Must-know
In plain words: Do not let a client send you a 10 GB JSON body. Wrap r.Body so reading more than N bytes fails, and turn that failure into 413.
Common misunderstanding: "Server.ReadTimeout or MaxHeaderBytes limit the body." MaxHeaderBytes only covers headers. ReadTimeout bounds time, not size: it "is the maximum duration for reading the entire request, including the body", so a slow trickle is cut when it expires, but a fast client can send gigabytes well within it. The http.Server doc adds that because ReadTimeout "does not let Handlers make per-request decisions on each request body's acceptable deadline or upload rate, most users will prefer to use ReadHeaderTimeout"; per-route budgets then come from ResponseController.SetReadDeadline (Go 1.20) or a context timeout, and size from MaxBytesReader. Second: "io.LimitReader is enough." It silently truncates, so you parse half a body; MaxBytesReader returns an error and "If possible, it tells the ResponseWriter to close the connection after the limit has been reached".
Definition: r.Body = http.MaxBytesReader(w, r.Body, n) (or http.MaxBytesHandler(h, n), Go 1.18). Reads beyond n return *http.MaxBytesError (Go 1.19) whose text is http: request body too large; match it with errors.As and answer 413 (http.StatusRequestEntityTooLarge, status text "Request Entity Too Large", RFC 9110 calls it "Content Too Large").
1 bodylimit mw r.Body = MaxBytesReader(w, r.Body, 64)
2 handler json.NewDecoder(r.Body).Decode(&in) reads byte 65
3 MaxBytesReader returns *MaxBytesError{Limit: 64}; connection marked to close
4 handler errors.As(err, &tooBig) -> 413 "body larger than 64 bytes"Real scenario: a JSON API taking at most 1 MB; an upload endpoint with its own 100 MB limit (a separate route group); a webhook receiver protecting itself from a misbehaving sender; a decompression bomb (limit the decompressed reader too).
| Endpoint | Limit | Where |
|---|---|---|
| JSON API | 1 MB | Route group (after snippet) |
| File upload | 100 MB, streamed to object storage | Its own route, see File Uploads & S3 |
| Webhook | 256 KB | Webhook group |
| Laravel | post_max_size, upload_max_filesize (php.ini), validation max: | PHP and request validation |
Fix / how to use it:
// Package bodylimit caps request bodies with http.MaxBytesReader and turns
// the resulting *http.MaxBytesError into 413 Content Too Large.
package bodylimit
import (
"encoding/json"
"errors"
"net/http"
)
// Middleware is http.MaxBytesHandler spelled out, so the cap is visible.
func Middleware(n int64) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
r.Body = http.MaxBytesReader(w, r.Body, n)
next.ServeHTTP(w, r)
})
}
}
// CreateOrder decodes JSON and maps the limit error to 413.
func CreateOrder(w http.ResponseWriter, r *http.Request) {
var in struct {
SKU string `json:"sku"`
Qty int `json:"qty"`
}
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
var tooBig *http.MaxBytesError
if errors.As(err, &tooBig) {
http.Error(w, "body larger than "+itoa(tooBig.Limit)+" bytes", http.StatusRequestEntityTooLarge)
return
}
http.Error(w, "bad json", http.StatusBadRequest)
return
}
w.WriteHeader(http.StatusCreated)
}
func itoa(n int64) string { b, _ := json.Marshal(n); return string(b) }package bodylimit
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
)
func TestBodyLimit(t *testing.T) {
h := Middleware(64)(http.HandlerFunc(CreateOrder))
small := `{"sku":"A1","qty":2}`
big := `{"sku":"` + strings.Repeat("x", 1000) + `","qty":1}`
for body, want := range map[string]int{small: 201, big: 413} {
rec := httptest.NewRecorder()
h.ServeHTTP(rec, httptest.NewRequest("POST", "/orders", strings.NewReader(body)))
if rec.Code != want {
t.Errorf("len %d: code %d want %d (%s)", len(body), rec.Code, want, rec.Body.String())
}
}
}Authentication middleware passing identity via context Must-know
In plain words: The auth middleware checks the token or session once, and if it is valid, stores who the caller is in the request context. Handlers read the identity with a typed accessor; they never parse tokens themselves.
Common misunderstanding: "Use a string key like "user" in the context." Any package can then read or overwrite it; the context docs say a key "should not be of type string or any other built-in type to avoid collisions between packages". Use context keys (unexported type), one per value, and export only the accessor. Second: "401 and 403 are the same." 401 means "who are you?" (send WWW-Authenticate); 403 means "I know who you are, and no". Keep authentication and authorization as separate middlewares.
Definition: token := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer "), verify (JWT signature and claims, or a session store lookup), ctx := context.WithValue(r.Context(), principalKey{}, p), next.ServeHTTP(w, r.WithContext(ctx)). Compare secrets with crypto/subtle.ConstantTimeCompare. RequireScope reads the principal and answers 403. Token formats, sessions and password hashing are in Authentication in Go; context values in depth in context: values.
1 auth mw Authorization: Bearer t-reader -> verify -> Principal{user:2, scopes: []}
2 auth mw ctx = WithValue(ctx, principalKey{}, p); next(r.WithContext(ctx))
3 RequireScope PrincipalFrom(ctx) -> no "orders:write" -> 403
no header 401 + WWW-Authenticate: Bearer realm="api"
bad token 401 + WWW-Authenticate: Bearer error="invalid_token"Real scenario: a JWT-protected JSON API; a session cookie checked against Redis; an internal service-to-service call with an mTLS identity mapped to a principal; an admin area requiring an admin scope on top of login.
| Context key style | Collision-safe | Readable by other packages | Verdict |
|---|---|---|---|
"user" (string) | No | Yes, by accident | Do not |
type key string; key("user") | Mostly | Only via the type | Acceptable |
type principalKey struct{} + accessor | Yes | Only via PrincipalFrom | This page |
gin c.Set("user", u) | No (string map) | Yes | Framework convention |
Laravel $request->user() | n/a | Guard-managed | Framework convention |
Fix / how to use it:
// Package auth verifies a bearer token and passes the caller's identity to
// handlers through the request context under an unexported key.
package auth
import (
"context"
"crypto/subtle"
"net/http"
"strings"
)
// Principal is who is calling.
type Principal struct {
Subject string
Scopes []string
}
type principalKey struct{}
// PrincipalFrom is the only way to read the identity.
func PrincipalFrom(ctx context.Context) (Principal, bool) {
p, ok := ctx.Value(principalKey{}).(Principal)
return p, ok
}
// Verifier checks a token; in production a JWT or session lookup.
type Verifier func(ctx context.Context, token string) (Principal, bool)
// StaticTokens is a demo Verifier with constant-time comparison.
func StaticTokens(tokens map[string]Principal) Verifier {
return func(_ context.Context, token string) (Principal, bool) {
for t, p := range tokens {
if subtle.ConstantTimeCompare([]byte(t), []byte(token)) == 1 {
return p, true
}
}
return Principal{}, false
}
}
// Middleware rejects requests without a valid bearer token with 401.
func Middleware(verify Verifier) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
token, ok := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ")
if !ok || token == "" {
w.Header().Set("WWW-Authenticate", `Bearer realm="api"`)
http.Error(w, "missing bearer token", http.StatusUnauthorized)
return
}
p, ok := verify(r.Context(), token)
if !ok {
w.Header().Set("WWW-Authenticate", `Bearer error="invalid_token"`)
http.Error(w, "invalid token", http.StatusUnauthorized)
return
}
ctx := context.WithValue(r.Context(), principalKey{}, p)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
}
// RequireScope is authorization layered on top: 403, not 401.
func RequireScope(scope string) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
p, _ := PrincipalFrom(r.Context())
for _, s := range p.Scopes {
if s == scope {
next.ServeHTTP(w, r)
return
}
}
http.Error(w, "forbidden", http.StatusForbidden)
})
}
}package auth
import (
"net/http"
"net/http/httptest"
"testing"
)
func TestAuth(t *testing.T) {
verify := StaticTokens(map[string]Principal{
"t-admin": {Subject: "user:1", Scopes: []string{"orders:write"}},
"t-reader": {Subject: "user:2"},
})
var who string
h := Middleware(verify)(RequireScope("orders:write")(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
p, _ := PrincipalFrom(r.Context())
who = p.Subject
})))
for hdr, want := range map[string]int{"": 401, "Bearer nope": 401, "Bearer t-reader": 403, "Bearer t-admin": 200} {
r := httptest.NewRequest("POST", "/orders", nil)
if hdr != "" {
r.Header.Set("Authorization", hdr)
}
rec := httptest.NewRecorder()
h.ServeHTTP(rec, r)
if rec.Code != want {
t.Errorf("%q: %d want %d", hdr, rec.Code, want)
}
}
if who != "user:1" {
t.Fatalf("principal not passed: %q", who)
}
}http.CrossOriginProtection (Go 1.25) and CSRF Important
In plain words: CSRF is another site making the user's browser send a state-changing request to you, with the user's cookies. Since Go 1.25 the standard library has a middleware that rejects non-safe cross-origin browser requests using the Sec-Fetch-Site header that browsers add, with no tokens.
Common misunderstanding: "My CORS config prevents CSRF." A cross-site HTML form POST is a simple request: no preflight, the server receives it and acts. MDN on simple requests: "anyone writing a server must already be protecting against cross-site request forgery (CSRF)". Second: "GET is protected too." CrossOriginProtection always allows GET, HEAD and OPTIONS ("It's important that applications do not perform any state changing actions due to requests with safe methods").
Definition: p := http.NewCrossOriginProtection(); p.AddTrustedOrigin("https://admin.example.test") allows an exact scheme://host[:port]; p.AddInsecureBypassPattern("POST /webhooks/") exempts routes with ServeMux pattern syntax; p.SetDenyHandler(h) replaces the default 403; p.Handler(next) is the middleware and p.Check(r) the bare check. The rule in csrf.go: safe methods pass; Sec-Fetch-Site of same-origin or none passes, any other value is rejected unless exempt; with no Sec-Fetch-Site, an Origin whose host equals Host passes, no Origin at all passes (non-browser client), otherwise reject. The OWASP CSRF cheat sheet names it: "Starting from 1.25, Go developers can rely on the built-in CrossOriginProtection type." Errors: cross-origin request detected from Sec-Fetch-Site header, or cross-origin request detected, and/or browser is out of date: Sec-Fetch-Site is missing, and Origin does not match Host.
1 evil.example.test page: <form method=POST action=https://bank.example.test/transfer> auto-submits
2 browser POST /transfer Cookie: session=... Sec-Fetch-Site: cross-site
3 Check method POST, Sec-Fetch-Site cross-site, not trusted, no bypass -> error
4 Handler 403 "cross-origin request detected from Sec-Fetch-Site header"
same page on bank.example.test: Sec-Fetch-Site: same-origin -> handler runsReal scenario: a server-rendered admin with cookie sessions; a legacy app moving off hidden-field tokens; a payment webhook that must be exempt (bypass pattern plus signature check); an SSO callback that is a cross-site POST by design.
| Defence | Needs client changes | Covers | Go |
|---|---|---|---|
http.CrossOriginProtection (Go 1.25) | No | Modern browsers via Sec-Fetch-Site; old ones via Origin/Host | stdlib |
| Synchronizer token | Hidden field or header | All browsers | gorilla/csrf, hand-made |
SameSite=Lax/Strict cookies | No | Cross-site cookie sending | http.Cookie{SameSite: ...} |
Bearer tokens in Authorization | Client stores token | Not sent automatically, so no CSRF | auth middleware |
Laravel PreventRequestForgery (in the web group) / @csrf | Hidden field | web group | built in |
Fix / how to use it: the module says go 1.24, so the implementation file starts with //go:build go1.25 (a file-level version upgrade); doc.go keeps the package non-empty for older toolchains. Attack background is in OWASP Top 10.
//go:build go1.25
package csrf
import "net/http"
// Protect rejects non-safe cross-origin browser requests with 403.
// Safe methods (GET, HEAD, OPTIONS) always pass, so they must not change state.
func Protect(trusted []string, bypass []string) (func(http.Handler) http.Handler, error) {
p := http.NewCrossOriginProtection()
for _, o := range trusted {
if err := p.AddTrustedOrigin(o); err != nil { // "scheme://host[:port]"
return nil, err
}
}
for _, pat := range bypass {
p.AddInsecureBypassPattern(pat) // e.g. "POST /webhooks/stripe"
}
return p.Handler, nil
}//go:build go1.25
package csrf
import (
"net/http"
"net/http/httptest"
"testing"
)
func TestCrossOriginProtection(t *testing.T) {
mw, err := Protect([]string{"https://admin.example.test"}, []string{"POST /webhooks/"})
if err != nil {
t.Fatal(err)
}
h := mw(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}))
cases := []struct {
name, method, path, site, origin string
want int
}{
{"same-origin POST", "POST", "/transfer", "same-origin", "", 200},
{"cross-site POST", "POST", "/transfer", "cross-site", "https://evil.example.test", 403},
{"cross-site GET is safe", "GET", "/transfer", "cross-site", "https://evil.example.test", 200},
{"trusted origin", "POST", "/transfer", "same-site", "https://admin.example.test", 200},
{"bypass pattern", "POST", "/webhooks/pay", "cross-site", "https://psp.example.test", 200},
{"no headers: curl or server", "POST", "/transfer", "", "", 200},
{"old browser, Origin != Host", "POST", "/transfer", "", "https://evil.example.test", 403},
}
for _, c := range cases {
r := httptest.NewRequest(c.method, "http://bank.example.test"+c.path, nil)
if c.site != "" {
r.Header.Set("Sec-Fetch-Site", c.site)
}
if c.origin != "" {
r.Header.Set("Origin", c.origin)
}
rec := httptest.NewRecorder()
h.ServeHTTP(rec, r)
if rec.Code != c.want {
t.Errorf("%s: %d want %d", c.name, rec.Code, c.want)
}
}
}Request coalescing Good to know
In plain words: When 500 clients ask for the same expensive, identical thing at the same moment (a cache miss on a hot product), let one request do the work and give its answer to all of them.
Common misunderstanding: "Coalescing is caching." It deduplicates only calls in flight at the same time; once the first call returns, the next request runs again. Combine it with a cache to stop a stampede. Second: "coalesce every GET." Only responses identical for every caller with that key; never per-user data, or one user's response goes to another.
Definition: golang.org/x/sync/singleflight "provides a duplicate function call suppression mechanism": Group.Do(key, fn) makes sure "only one execution is in-flight for a given key at a time. If a duplicate comes in, the duplicate caller waits for the original to complete and receives the same results." As middleware, buffer the leader's response (httptest.NewRecorder is a handy buffer), then replay status, headers and body to every waiter. Singleflight's shared flag is true for the leader too once duplicates joined ("The return value shared indicates whether v was given to multiple callers"), so the snippet records leadership in the closure that singleflight actually runs and sets X-Coalesced: 1 only on followers. It uses DoChan, which registers the caller before returning; the test's hook counts registrations and releases the backend only after all 20 have joined, so it needs no sleeps. The leader's context is the leader's request; if that client disconnects, all waiters get the canceled result, so production code detaches the work (context.WithoutCancel plus a timeout).
t=0 req1 GET /price/A1 -> leader: backend called
t=1ms req2..req20 same key -> wait on the same call
t=100ms backend returns {"price":42}
t=100ms all 20 receive it; the 19 followers carry X-Coalesced: 1, the leader does not
(test: backend called 1 time, header on exactly 19 responses)Real scenario: a product page right after a cache flush; a config endpoint polled by thousands of clients; thundering herds after a deploy; a CDN origin shield doing the same at the edge ("request collapsing").
| Tool | Scope |
|---|---|
singleflight middleware (this page) | One process, in-flight only |
| Cache + singleflight on miss | Stampede protection |
| CDN request collapsing | Edge, per PoP |
NGINX proxy_cache_lock on | Reverse proxy |
Fix / how to use it:
// Package coalesce collapses identical concurrent GET requests into one
// call to the handler with golang.org/x/sync/singleflight; every waiter
// receives a copy of the same response.
package coalesce
import (
"bytes"
"net/http"
"net/http/httptest"
"golang.org/x/sync/singleflight"
)
type result struct {
code int
header http.Header
body []byte
}
// Middleware coalesces GETs by key(r). Only use it for responses that are
// identical for every caller with that key (no per-user data).
func Middleware(key func(*http.Request) string) func(http.Handler) http.Handler {
return middleware(key, nil)
}
// middleware takes a joined hook for tests: it runs once the caller is
// attached to the in-flight call (DoChan has registered it).
func middleware(key func(*http.Request) string, joined func()) func(http.Handler) http.Handler {
var g singleflight.Group
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
next.ServeHTTP(w, r)
return
}
leader := false // set only inside the closure singleflight actually runs
ch := g.DoChan(key(r), func() (any, error) {
leader = true
rec := httptest.NewRecorder() // buffer once, replay to all
next.ServeHTTP(rec, r)
return result{rec.Code, rec.Header().Clone(), rec.Body.Bytes()}, nil
})
if joined != nil {
joined()
}
res := <-ch // the receive orders the write of leader before this read
v := res.Val.(result)
for k, vs := range v.header {
w.Header()[k] = append([]string(nil), vs...)
}
// singleflight's Shared is true for the leader too once anyone
// joined; mark only the followers that got a copy.
if res.Shared && !leader {
w.Header().Set("X-Coalesced", "1")
}
w.WriteHeader(v.code)
_, _ = bytes.NewReader(v.body).WriteTo(w)
})
}
}package coalesce
import (
"net/http"
"net/http/httptest"
"sync"
"sync/atomic"
"testing"
)
const callers = 20
// Round 1, item 10: no sleeps. The joined hook runs after DoChan has
// registered a caller with the in-flight call, so when it has fired 20
// times every caller is attached and the backend can be released.
func TestConcurrentGetsHitBackendOnce(t *testing.T) {
var calls atomic.Int32
release := make(chan struct{})
backend := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
calls.Add(1)
<-release
_, _ = w.Write([]byte(`{"price":42}`))
})
var joined atomic.Int32
hook := func() {
if joined.Add(1) == callers {
close(release)
}
}
h := middleware(func(r *http.Request) string { return r.URL.Path }, hook)(backend)
var wg sync.WaitGroup
recs := make([]*httptest.ResponseRecorder, callers)
for i := range recs {
recs[i] = httptest.NewRecorder()
wg.Add(1)
go func(rec *httptest.ResponseRecorder) {
defer wg.Done()
h.ServeHTTP(rec, httptest.NewRequest("GET", "/price/A1", nil))
}(recs[i])
}
wg.Wait()
if n := calls.Load(); n != 1 {
t.Fatalf("backend called %d times, want 1", n)
}
marked := 0
for _, rec := range recs {
if rec.Body.String() != `{"price":42}` {
t.Fatalf("body %q", rec.Body.String())
}
if rec.Header().Get("X-Coalesced") == "1" {
marked++
}
}
// Round 1, item 9: only followers are marked, not the leader.
if marked != callers-1 {
t.Fatalf("X-Coalesced on %d responses, want %d (followers only)", marked, callers-1)
}
}httptest for middleware Must-know
In plain words: A middleware is a function from handler to handler, so a test wraps a tiny fake handler, sends a request built with httptest.NewRequest, records the response with httptest.NewRecorder, and asserts the status, headers and what the inner handler saw.
Common misunderstanding: "I need a running server to test middleware." Only for behaviour that depends on the real connection (client-side gzip decoding, Hijack, timeouts on the wire); use httptest.NewServer for those, as the end-to-end test does. Second: "Test only through the full stack." Unit-test each middleware with a fake next that records what it received, then one end-to-end test for ordering.
Definition: httptest.NewRequest(method, target, body) builds a server-side request (RemoteAddr is 192.0.2.1:1234, overridable); httptest.NewRecorder() implements ResponseWriter and Flusher (rec.Flushed), exposing Code, Header(), Body. httptest.NewServer(h) starts a real listener on 127.0.0.1 with srv.URL. Fake clocks (now func() time.Time in the rate limiter) make time-based tests deterministic; see Testing & Benchmarking.
1 next := http.HandlerFunc(func(w, r) { seen = requestid.From(r.Context()) })
2 h := requestid.Middleware(next)
3 req := httptest.NewRequest("GET", "/", nil); req.Header.Set("X-Request-Id", "abc-123")
4 rec := httptest.NewRecorder(); h.ServeHTTP(rec, req)
5 assert seen == "abc-123" && rec.Header().Get("X-Request-Id") == "abc-123"Real scenario: a regression test for "preflight must not require a token"; asserting Vary on every CORS response; proving the logging wrapper keeps Flush; table tests for real-IP edge cases.
| What to assert | How |
|---|---|
| Short-circuit | Inner handler flag stays false; rec.Code |
| Context value | Inner handler copies it out |
| Header set | rec.Header().Get(...) |
| Body transformed | Decode rec.Body (gzip reader) |
| Order | A shared log slice, as in the chain test |
| Panic handling | Inner handler panics; check code and log buffer |
| Wire behaviour | httptest.NewServer + http.Client |
Fix / how to use it: every package in this chapter's module has such a test; the chain and requestid tests above are the minimal shape.
chi/gin middleware comparison Important
In plain words: chi uses exactly the func(http.Handler) http.Handler shape, so everything on this page plugs into chi unchanged. gin has its own gin.HandlerFunc taking *gin.Context, with c.Next() and c.Abort() instead of calling next.
Common misunderstanding: "gin's c.Abort() stops the current function." Its doc: "Abort prevents pending handlers from being called. Note that this will not stop the current handler." You still return. Second: "chi's middleware package is safe by default." Its RealIP is now deprecated as spoofable; use ClientIPFromXFF with trusted CIDRs.
Definition: chi: r.Use(mw...) for the router, r.Group(func(r chi.Router){ r.Use(...) }) and r.With(mw...) for subsets; chi.Chain(mw...).Handler(h). gin: gin.Default() is gin.New() plus engine.Use(Logger(), Recovery()); c.Next() runs "the pending handlers in the chain inside the calling handler"; values via c.Set/c.Get; standard middleware can be adapted with gin.WrapH, but c.Next() semantics do not cross the adapter.
chi: r.Use(middleware.RequestID, middleware.Logger, middleware.Recoverer)
r.With(auth).Post("/orders", create) same func(http.Handler) http.Handler
gin: func Auth() gin.HandlerFunc { return func(c *gin.Context) {
if !ok { c.AbortWithStatusJSON(401, ...); return }
c.Set("user", u); c.Next() // after c.Next(): response phase
} }Real scenario: a team moving from gin to the standard mux after Go 1.22 routing; reusing rs/cors and promhttp in both; a gin Recovery() that already handles broken pipes (it checks syscall.EPIPE/ECONNRESET and does not try to write a 500 to a dead connection).
| Concern | net/http (this page) | chi v5 | gin |
|---|---|---|---|
| Shape | func(http.Handler) http.Handler | same | func(*gin.Context) |
| Continue | next.ServeHTTP(w, r) | same | c.Next() |
| Stop | return without next | same | c.Abort() + return |
| Request ID | requestid package | middleware.RequestID | gin-contrib/requestid |
| Logging | slog middleware | middleware.Logger | gin.Logger() |
| Recover | recoverer | middleware.Recoverer (re-panics ErrAbortHandler) | gin.Recovery() |
| Real IP | right-to-left XFF | ClientIPFromXFF, ClientIPFromHeader | c.ClientIP() + SetTrustedProxies |
| Compression | compress | middleware.Compress | gin-contrib/gzip |
| Timeout | context deadline | middleware.Timeout (504) | gin-contrib/timeout |
| Throttle | x/time/rate | middleware.Throttle (concurrency) | third-party |
| Body limit | MaxBytesReader | middleware.RequestSize | MaxBytesReader by hand |
| CORS | hand-made or rs/cors | go-chi/cors (an rs/cors fork) | gin-contrib/cors |
| Values | context.WithValue + accessor | same | c.Set / c.Get |
Mechanics
How net/http calls your stack Important
Per connection, conn.serve runs a loop: read a request, build *http.response (the real ResponseWriter), call Server.Handler.ServeHTTP(w, r) (your outermost middleware), then finish the response (flush, chunked trailer, keep-alive decision). The same goroutine runs every layer; a middleware adds a function call and maybe an allocation for a wrapper.
1 accept conn -> go c.serve(ctx)
2 defer: if err := recover(); err != nil && err != ErrAbortHandler -> logf("http: panic serving %v: %v\n%s", ...)
3 for { w, err := c.readRequest(ctx)
4 serverHandler{c.server}.ServeHTTP(w, w.req) -> requestid -> logging -> ... -> mux -> handler
5 w.finishRequest() -> unwritten status becomes 200, body flushed
6 if !w.shouldReuseConnection() { break } }Rules that follow from it: headers are mutable until the first final (2xx–5xx) WriteHeader or Write (then frozen, so header middlewares must act before next; 1xx codes such as 103 are sent at once and do not freeze the map); WriteHeader twice logs http: superfluous response.WriteHeader call from <func> (<file>:<line>); using w after ServeHTTP returned is invalid; r.Context() is canceled when the outermost ServeHTTP returns.
Exact error texts Must-know
| Text | Where it comes from |
|---|---|
http: panic serving 10.0.0.5:51234: runtime error: ... | conn.serve recover, written to Server.ErrorLog |
http: request body too large | *http.MaxBytesError from MaxBytesReader |
http: Handler timeout | http.ErrHandlerTimeout, writes after TimeoutHandler fired |
http: superfluous response.WriteHeader call from ... | Second WriteHeader |
http: wrote more than the declared Content-Length | http.ErrContentLength, e.g. a stale Content-Length |
feature not supported (matches http.ErrNotSupported) | ResponseController without a capable writer |
cross-origin request detected from Sec-Fetch-Site header | CrossOriginProtection.Check |
cross-origin request detected, and/or browser is out of date: Sec-Fetch-Site is missing, and Origin does not match Host | CrossOriginProtection.Check |
invalid origin "x": scheme is required | AddTrustedOrigin |
429 Too Many Requests / Retry-After: 2 | Rate limiter (RFC 6585 §4) |
Browser console CORS error naming a missing Access-Control-Allow-Origin (wording varies by browser) | Unknown origin or failed preflight |
Browser console CORS error about the * wildcard in credentials mode include (wording varies by browser) | * with credentials |
Allocation and cost Good to know
A middleware that only sets headers costs a closure call and a few map writes. A wrapper writer is one small allocation per request. The expensive ones are compression (CPU proportional to body size; pool the writers), logging (formatting and I/O; use LogAttrs and an async or buffered sink in very hot paths), and the rate limiter's mutex (shard the map by key hash if one lock becomes a hotspot). rs/cors publishes 51 ns/op for its default handler and 0 allocations.
Solving the classic problems
| Bug | Symptom | Fix | Cost |
|---|---|---|---|
| Status not captured | Every log line says 200 or 0 | Recorder with WriteHeader + 200 default | One wrapper |
Wrapper hides Flush/Hijack | SSE buffered, WebSocket upgrade fails | Unwrap() on every wrapper, ResponseController in handlers | One method |
| Recover outside logging (logging inside recover) | Panics invisible in logs and metrics | logging(recover(...)) | Reorder |
| Auth before CORS | Every preflight 401 | CORS before auth | Reorder |
* with credentials, or reflecting any Origin | Browser refuses, or any site reads user data | Allowlist + echo + Vary: Origin | Config |
Leftmost X-Forwarded-For | Rate limits and IP allowlists bypassed | Right-to-left with trusted CIDRs | Config of proxy ranges |
| Global limiter | One client throttles everyone | Per-key buckets with eviction | A map and a sweep |
Stale Content-Length with gzip | Hung or truncated responses | Delete it when compressing | One line |
Missing Vary: Accept-Encoding | CDN serves gzip to a client that cannot read it | Always add it | One line |
| Unbounded body | Memory spikes, OOM | MaxBytesReader + 413 | One wrapper |
Swallowing http.ErrAbortHandler | Intentional aborts become 500s with stacks | Re-panic it | One if |
| String context keys | Values overwritten by another package | Unexported key types + accessors | A few lines |
Fix the status code and keep Flush
The logging snippet is the reference: embed the writer, record the first final (non-1xx) WriteHeader, default to 200 on Write, add Unwrap. Its third test is the negative proof: a wrapper without Unwrap makes ResponseController.Flush fail.
Fix the order
Write the stack once, comment each line, and keep the end-to-end test in After green: it fails if CORS moves after auth (the preflight would get 401) or the limiter moves before real IP.
Fix CORS with credentials
Never Access-Control-Allow-Origin: * with cookies, never echo an unchecked Origin. Echo an allowlisted origin, add Allow-Credentials: true only if you need cookies, and Vary: Origin always. The CORS tests run the same cases against the hand-written middleware and rs/cors.
Fix IP-based limits behind a proxy
Configure the proxy CIDRs once, compute the client IP right to left in Real IP, key the rate limiter on the authenticated user when there is one, and keep IP only as a fallback.
Choosing
| Situation | Use | Extra technique | Reason |
|---|---|---|---|
| Standard library mux | Chain helper + func(http.Handler) http.Handler | Route groups as chains | No framework needed since Go 1.22 routing |
| chi router | r.Use, r.Group, r.With | chi's middleware package, minus RealIP | Same shape, more batteries |
| gin | gin.HandlerFunc, c.Next, c.Abort | gin.WrapH for stdlib handlers | Framework context |
| Correlating logs | Request ID + slog handler reading ctx | Forward the header downstream | One ID per request |
| Access logs | Logging middleware with status recorder | Unwrap | Status is invisible otherwise |
| Panics | Recover inside logging | Re-panic ErrAbortHandler; recover in goroutines too | Clean 500 + stack |
| Request budget | Context timeout middleware | TimeoutHandler for untrusted handlers | Streaming keeps working |
| Browser security | Security headers preset per API/HTML | CSP report-only first | Defence in depth |
| SPA on another origin | rs/cors with an allowlist | MaxAge to cut preflights | Correct Vary and credentials rules |
| Bandwidth | gzip at the edge, or middleware for dynamic JSON | Pool writers, min size, BREACH care | Fewer bytes |
| Abuse protection | Per-key x/time/rate | Redis for multi-replica, gateway first | 429 + Retry-After |
| Latency SLOs | Prometheus histogram by route | DefBuckets or tuned | Quantiles across instances |
| Big bodies | MaxBytesReader per route group | 413 mapping | Memory safety |
| Identity | Auth middleware + unexported key | Separate authorization | Typed, collision-free |
| Cookie-session forms | http.CrossOriginProtection (Go 1.25) | SameSite, bypass for webhooks | CSRF without tokens |
| Hot identical GETs | singleflight middleware | Cache + detach context | Stampede control |
In architecture: from a single process to a distributed system
Monolith: one process, one database
In a monolith the whole stack lives in NewServer: one global chain (request ID, logging, recover, real IP, headers, CORS, limiter, timeout, compression) around one mux, plus route-group chains (auth and body limit for /api, CSRF for the HTML admin, signature verification for /webhooks). Everything is in memory: the limiter's map, the singleflight group, the metrics registry. Example: a Go monolith behind one NGINX, trusted proxy 127.0.0.1/32, a 1 MB body limit, 10 req/s per user, and access logs shipped from stdout.
Modular monolith and multiple databases
Modules register their own routes and can bring their own route middleware (billing adds an idempotency-key middleware; admin adds a stricter limiter), but the global stack belongs to the platform module so the order cannot be changed by one team. The audit trail written by a logging or auth middleware goes to the module that owns it; for example a login audit table:
-- written by the auth middleware's failure path, read by the security team
CREATE TABLE auth_events (
id bigserial PRIMARY KEY,
at timestamptz NOT NULL DEFAULT now(),
request_id text NOT NULL,
client_ip inet NOT NULL,
subject text,
outcome text NOT NULL CHECK (outcome IN ('ok', 'invalid_token', 'missing_token', 'forbidden'))
);
CREATE INDEX ON auth_events (client_ip, at DESC);
-- who is hammering us with bad tokens in the last 10 minutes?
SELECT client_ip, count(*) AS failures
FROM auth_events
WHERE outcome <> 'ok' AND at > now() - interval '10 minutes'
GROUP BY client_ip ORDER BY failures DESC LIMIT 20;Microservices
Across services, some middleware moves to the edge and some must exist in every service. The API gateway (or ingress) does TLS, HSTS, CORS, coarse rate limits, compression and often authentication (validating the JWT once); internal services still run request ID (accepting the gateway's), logging, recover, metrics, timeouts and body limits, and re-check identity (an internal JWT or mTLS identity) rather than trusting a header. What crosses the boundary is headers: X-Request-Id and traceparent forwarded by an outgoing http.RoundTripper (the client-side twin of middleware), the remaining deadline (see context: deadline propagation), and the principal as a token. Example: browser → gateway (CORS, limit_req, JWT check) → orders service (request ID from header, logging, recover, 2 s timeout) → payments (same stack, mTLS identity). What does not survive: in-process limiter state, singleflight groups and any context value that was not serialised into a header.
Distributed data: replicas, caches, sharded databases, multi-region
With N replicas, an in-process limiter allows N × r per client, so real quotas live in Redis (a token bucket in a Lua script or INCR with EXPIRE per window) or at the gateway; the in-process limiter stays as a cheap per-instance guard. Coalescing per process still lets N replicas hit the origin once each; put a shared cache in front and coalesce on misses. Caches between client and service make Vary correctness critical: a CDN that ignores Vary: Origin leaks CORS responses across origins, one that ignores Vary: Accept-Encoding serves gzip to clients that did not ask. Multi-region adds more proxies to the X-Forwarded-For chain: the trusted CIDR list must include every hop you own, or the client IP becomes your own edge. Algorithms and Redis designs: Rate Limiting algorithms.
Scaling path: 1×, 10×, 100×
| Load | What changes | Middleware practice |
|---|---|---|
| 1× (one instance) | Bugs are invisible | Correct order, status capture, Unwrap, body limit, recover; tests for each |
| 10× (several instances behind a load balancer) | Proxy hops, per-instance limits drift | Trusted-proxy real IP, Redis-backed quotas, histograms by route, compression at the edge |
| 100× (many services, CDN, multi-region) | Edge does most of it, cardinality and cost matter | Gateway for CORS/limits/auth, services keep ID/logging/recover/timeouts, sampled logs, native histograms, coalescing + shared cache |
Lab
1. Run the tests (real)
cd docs/snippets/go/middlewares/go
go vet ./... && go test -race -count=1 ./...
# ok academy/middlewares/after 1.506s
# ok academy/middlewares/auth 1.331s
# ok academy/middlewares/before 1.490s
# ok academy/middlewares/bodylimit 1.485s
# ok academy/middlewares/chain 1.463s
# ? academy/middlewares/cmd/server [no test files]
# ok academy/middlewares/coalesce 1.557s
# ok academy/middlewares/compress 1.426s
# ok academy/middlewares/cors 1.437s
# ok academy/middlewares/csrf 1.432s
# ok academy/middlewares/logging 1.432s
# ok academy/middlewares/metrics 1.381s
# ok academy/middlewares/ratelimit 1.345s
# ok academy/middlewares/realip 1.408s
# ok academy/middlewares/recoverer 1.280s
# ok academy/middlewares/requestid 1.273s
# ok academy/middlewares/secheaders 1.258s
# ok academy/middlewares/timeout 1.298s2. See the onion order and the gzip ratio (real)
go test -count=1 -v ./chain ./compress -run 'TestChainOrderIsOnion|TestShortCircuit|TestGzipWhenAccepted'
# --- PASS: TestChainOrderIsOnion (order "a> b> c> handler <c <b <a")
# --- PASS: TestShortCircuitSkipsInnerLayers
# compress_test.go:46: identity 5000 bytes -> gzip 77 bytes3. Spoof X-Forwarded-For (real)
go test -count=1 -v ./realip
# --- PASS: TestRealIP (direct client ignores header; spoofed leftmost skipped; garbage fails closed)4. Preflight and headers with curl (real)
The module has a runnable server: cmd/server wires after.NewServer with token dev-token (principal user:1), the allowed origin https://app.example.test, a limiter of 1 request/s per client with burst 2, a 2 s handler deadline and no trusted proxies (-trusted-proxies 10.0.0.0/8,... adds some).
// Command server runs the after.NewServer stack on a local port for the
// chapter's curl labs:
//
// go run ./cmd/server -addr 127.0.0.1:8080
//
// Token "dev-token" is accepted for user:1; origin https://app.example.test
// is allowed; the limiter allows 1 request/s per client with a burst of 2.
package main
import (
"flag"
"log/slog"
"net/http"
"net/netip"
"os"
"strings"
"time"
"academy/middlewares/after"
"academy/middlewares/auth"
"academy/middlewares/ratelimit"
)
func main() {
addr := flag.String("addr", "127.0.0.1:8080", "listen address")
proxies := flag.String("trusted-proxies", "", "comma-separated CIDRs whose X-Forwarded-For is trusted")
flag.Parse()
var trusted []netip.Prefix
for _, c := range strings.Split(*proxies, ",") {
if c = strings.TrimSpace(c); c != "" {
trusted = append(trusted, netip.MustParsePrefix(c))
}
}
log := slog.New(slog.NewTextHandler(os.Stdout, nil))
h := after.NewServer(after.Deps{
Log: log,
Verify: auth.StaticTokens(map[string]auth.Principal{"dev-token": {Subject: "user:1"}}),
Origins: map[string]bool{"https://app.example.test": true},
Proxies: trusted,
PerIP: ratelimit.New(1, 2),
Deadline: 2 * time.Second,
})
srv := &http.Server{Addr: *addr, Handler: h, ReadHeaderTimeout: 5 * time.Second}
log.Info("listening", "addr", *addr)
if err := srv.ListenAndServe(); err != nil {
log.Error("server stopped", "err", err)
os.Exit(1)
}
}cd docs/snippets/go/middlewares/go
go run ./cmd/server -addr 127.0.0.1:8080 # terminal 1; prints level=INFO msg=listening
# terminal 2:
curl -si -X OPTIONS http://127.0.0.1:8080/api/orders \
-H 'Origin: https://app.example.test' -H 'Access-Control-Request-Method: POST'
# HTTP/1.1 204 No Content
# Access-Control-Allow-Credentials: true
# Access-Control-Allow-Headers: Authorization, Content-Type
# Access-Control-Allow-Methods: GET, POST
# Access-Control-Allow-Origin: https://app.example.test
# Access-Control-Max-Age: 600
# Cache-Control: no-store
# Content-Security-Policy: default-src 'none'; frame-ancestors 'none'
# Referrer-Policy: no-referrer
# Vary: Origin
# Vary: Access-Control-Request-Method
# Vary: Access-Control-Request-Headers
# X-Content-Type-Options: nosniff
# X-Frame-Options: DENY
# X-Request-Id: 9e877bec2021c649db0b7e49
curl -si --compressed -H 'Authorization: Bearer dev-token' http://127.0.0.1:8080/api/orders
# HTTP/1.1 200 OK
# Content-Encoding: gzip
# Content-Type: application/json
# Vary: Origin
# Vary: Accept-Encoding
# X-Request-Id: d6c9f1f5e6b3642ad4362016
# Content-Length: 65
# {"orders":["order-1"],"owner":"user:1"}The preflight is answered by CORS before the limiter and does not use a token; the GET does. The Content-Length: 65 is the compressed size: the middleware deleted the handler's length, and net/http computed a new one because the whole compressed body fitted in its buffer when the handler returned.
5. Hit the limiter (real)
Restart the server first so the bucket for 127.0.0.1 is full (the GET in lab 4 used a token, and a readiness probe with curl would use one too; wait for the listening log line instead):
for i in 1 2 3; do curl -s -o /dev/null -w '%{http_code} ' http://127.0.0.1:8080/healthz; done
# 200 200 429
curl -si http://127.0.0.1:8080/healthz | grep -i -E '^HTTP|retry-after'
# HTTP/1.1 429 Too Many Requests
# Retry-After: 16. Panic in a handler (asserted by a test; curl variant expected, not run)
TestPanicIsLoggedWith500 in after/round1_test.go wraps a panicking handler in Stack and asserts the 500 and the log lines. Against the running server, add a route that panics and call it: the client gets 500 Internal Server Error, the log has level=ERROR msg="panic in handler" ... stack=... followed by the logging middleware's status=500, and the server's ErrorLog stays silent because the panic never reached conn.serve.
For PHP/Laravel developers
Laravel middleware is the same onion with a different shape. Its docs: "Middleware provide a convenient mechanism for inspecting and filtering HTTP requests entering your application", and "It's best to envision middleware as a series of "layers" HTTP requests must pass through before they hit your application." A Laravel middleware is a class with handle(Request $request, Closure $next): Response; work before $next($request) is "before" middleware, work on the returned $response is "after" middleware. Global middleware is registered in bootstrap/app.php with ->withMiddleware(...) (append, prepend, insertBefore, insertAfter), and the web and api groups play the role of route-group chains. Laravel 13's default global stack (as listed for $middleware->use([...])) contains ValidatePathEncoding, InvokeDeferredCallbacks, TrustProxies (real IP), HandleCors (configured in config/cors.php: allowed_origins, supports_credentials, max_age), PreventRequestsDuringMaintenance, ValidatePostSize (a body limit), TrimStrings and ConvertEmptyStringsToNull; it has no throttling and no CSRF check. CSRF protection is PreventRequestForgery in the web group. Rate limiting is route middleware: ThrottleRequests behind the throttle alias (throttle:api, defined with RateLimiter::for(...); "a response with a 429 HTTP status code will automatically be returned"). Terminable middleware's terminate runs "after the HTTP response has been sent to the browser".
// Laravel: before + after in one middleware; Go: the same in a closure around next.ServeHTTP.
public function handle(Request $request, Closure $next): Response
{
$start = hrtime(true); // before
$response = $next($request); // inner layers + controller
$response->headers->set('X-Content-Type-Options', 'nosniff');
Log::info('http request', ['status' => $response->getStatusCode(), 'ms' => (hrtime(true) - $start) / 1e6]);
return $response; // after
}| Laravel | Go |
|---|---|
handle($request, Closure $next) | func(next http.Handler) http.Handler |
$next($request) returns a Response object you can inspect | next.ServeHTTP(w, r) streams; wrap w to observe |
bootstrap/app.php withMiddleware (append/prepend) | Chain(...) in NewServer |
web / api middleware groups | Route-group chains |
TrustProxies | Real-IP middleware with trusted CIDRs |
HandleCors + config/cors.php | rs/cors options |
throttle:api route middleware + RateLimiter::for | Per-key x/time/rate (+ Redis) |
PreventRequestForgery in the web group | http.CrossOriginProtection or tokens |
ValidatePostSize (global) | MaxBytesReader middleware |
$request->user() set by the auth guard | auth.PrincipalFrom(r.Context()) |
Terminable middleware terminate() | Work after next returns, or WithoutCancel goroutine |
| Exception handler renders a 500 | Recover middleware |
Common misconceptions
| Belief | Reality |
|---|---|
| Order of middleware does not matter | It decides what each layer sees: logging outside recover, CORS before auth, real IP before limits |
Chain(a, b, c) runs c first | a runs first on the way in and last on the way out |
Embedding http.ResponseWriter keeps Flush | Only Header, Write, WriteHeader are promoted; add Unwrap |
| Without recover the server crashes | net/http recovers per connection; you lose the 500 and your log line |
Recover everything, including ErrAbortHandler | Re-panic it: it is a deliberate abort |
| A timeout middleware stops the handler | It cancels ctx; the handler must stop itself |
| Security headers secure an API | They instruct browsers; non-browser clients ignore them |
Access-Control-Allow-Origin: * works with cookies | Browsers reject it; echo an allowlisted origin |
| CORS stops CSRF | Simple cross-site requests reach the server; use CSRF protection |
The leftmost X-Forwarded-For is the client | It is whatever the client sent; walk right to left from trusted hops |
One rate.Limiter is enough | Per-key buckets, eviction, and shared state across replicas |
| Compression is always good | Not for small or already compressed bodies, and mind BREACH |
Keep Content-Length when gzipping | It describes the uncompressed body; delete it |
| A string context key is fine | Use an unexported key type and an accessor |
| Label metrics by URL path | Label by route pattern to bound cardinality |
Cheat sheet
| Topic | Remember |
|---|---|
| Shape | func(next http.Handler) http.Handler; deps in the constructor |
| Chain | Chain(a, b, c)(h) == a(b(c(h))); first listed is outermost |
| Order | ID → logging → recover → real IP → headers → CORS → limiter → timeout → compress → mux → route chain |
| Request ID | Validate inbound, else mint; ctx + response header |
| Logging | Recorder: first final (non-1xx) WriteHeader, 200 default, bytes, Unwrap |
| ResponseController | http.NewResponseController(w).Flush() follows Unwrap (Go 1.20) |
| Recover | Inside logging; re-panic http.ErrAbortHandler; 500 only if nothing written |
| Timeout | WithTimeout(r.Context()); handler maps DeadlineExceeded to 504 |
| Headers | CSP, HSTS (TLS only), nosniff, X-Frame-Options/frame-ancestors, Referrer-Policy, Permissions-Policy |
| CORS | Allowlist, echo origin, no * with credentials, Vary: Origin, preflight 204 before auth |
| Compression | Vary: Accept-Encoding, Content-Encoding: gzip, delete Content-Length, skip encoded, pool, BREACH |
| Real IP | Right to left over trusted CIDRs; never the leftmost |
| Rate limit | Per key x/time/rate, evict idle, 429 + Retry-After; Redis across replicas |
| Metrics | Histogram by route/method/code; DefBuckets; promhttp labels code, method |
| Body | MaxBytesReader → *MaxBytesError → 413 |
| Auth | Verify once, principal in ctx under struct{} key; 401 vs 403 |
| CSRF | http.CrossOriginProtection (Go 1.25): Sec-Fetch-Site, trusted origins, bypass patterns |
| Tests | httptest.NewRequest + NewRecorder; NewServer for the wire |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — What is the type of a Go HTTP middleware, and what three things can it do? Must-know
Answer
Answer: func(http.Handler) http.Handler. It can run code before calling next.ServeHTTP, run code after it returns, or answer by itself and never call next (short-circuit). It can also replace r (a new context) or w (a wrapper) for the inner layers.
2 — Chain(a, b, c)(h): in what order do the "before" and "after" parts run? Must-know
Answer
Answer: Before parts run a, b, c; then the handler; after parts run c, b, a. Chain(a, b, c)(h) equals a(b(c(h))), so the first listed is the outermost layer.
3 — Why does the logging middleware go outside the recover middleware? Must-know
Answer
Answer: If recover is outside, a panic unwinds through the logging frame before anything recovers it, so the request is never logged and the 500 is invisible. With logging(recover(h)), recover turns the panic into a 500 and logging records status=500.
4 — How does a logging middleware learn the status code, and what are the two rules for getting it right? Important
Answer
Answer: By wrapping ResponseWriter in a recorder that overrides WriteHeader and Write. Record the first final WriteHeader, forwarding 1xx informational codes such as 103 without recording them (later final calls are ignored as superfluous), and treat a Write without WriteHeader, or no write at all, as 200.
5 — After adding a metrics middleware, server-sent events stop streaming. Why, and what is the fix? Important
Answer
Answer: The wrapper embeds http.ResponseWriter, which promotes only Header, Write and WriteHeader, so w.(http.Flusher) fails and nothing is flushed. Add Unwrap() http.ResponseWriter to the wrapper and flush with http.NewResponseController(w).Flush() (Go 1.20), which follows Unwrap to the original writer.
6 — Why must a recover middleware re-panic http.ErrAbortHandler? Important
Answer
Answer: It is the sentinel a handler (or httputil.ReverseProxy) uses to abort the response on purpose: the client sees an interrupted response and net/http suppresses the stack trace. Recovering it would turn an intentional abort into a logged 500.
7 — A browser call with cookies fails although the API sends Access-Control-Allow-Origin: *. What is wrong, and what must the response contain instead? Must-know
Answer
Answer: For credentialed requests the wildcard is not allowed. Echo the specific allowlisted origin, add Access-Control-Allow-Credentials: true, and Vary: Origin so caches do not reuse the response for another origin. Never echo an unchecked Origin.
8 — Why does an authentication middleware placed before CORS break the SPA? Important
Answer
Answer: The preflight OPTIONS request carries no cookies or Authorization header, so auth answers 401 and the browser never sends the real request. CORS must answer preflights (204) before auth runs.
9 — What must a gzip middleware do with Content-Length, Vary and Content-Encoding, and when should it not compress? Important
Answer
Answer: Delete Content-Length (it describes the uncompressed body), add Vary: Accept-Encoding and set Content-Encoding: gzip. Skip clients without gzip in Accept-Encoding, HEAD, 204/304, bodies already encoded, small or already compressed content, and responses that mix secrets with reflected user input (BREACH).
10 — Your per-IP rate limiter reads the first address of X-Forwarded-For. How is it bypassed, and what is correct? Must-know
Answer
Answer: The leftmost entry is set by the client, so an attacker sends a new fake IP per request and gets a fresh bucket each time. Trust the header only when the TCP peer is your proxy, walk it right to left skipping your trusted CIDRs, and take the first untrusted address.
11 — What should the rate limiter middleware answer when a client's bucket is empty, and why not Wait? Important
Answer
Answer: 429 Too Many Requests with Retry-After set from the reservation's delay (RFC 6585 allows it). Wait would park a goroutine and keep a connection open for every excess request, which is the load the limiter exists to shed.
12 — How should an auth middleware pass the principal to handlers? Must-know
Answer
Answer: context.WithValue(r.Context(), principalKey{}, p) with an unexported key type, then next.ServeHTTP(w, r.WithContext(ctx)), and an exported accessor PrincipalFrom(ctx). A string key can collide with or be overwritten by any package.
13 — What does http.CrossOriginProtection check, and which requests does it always allow? Good to know
Answer
Answer: For non-safe methods it rejects requests whose Sec-Fetch-Site is not same-origin or none; without that header it compares the Origin host with Host, and allows requests with neither header (non-browser clients). GET, HEAD and OPTIONS always pass, as do trusted origins and bypass patterns. It arrived in Go 1.25.
14 — What is request coalescing and when is it unsafe? Good to know
Answer
Answer: Collapsing identical concurrent requests into one backend call (for example with singleflight.Group.Do) and giving every waiter the same response. It is unsafe for per-user or otherwise caller-specific responses, and the shared call must not depend on the leader's client staying connected.
Glossary
| Term | Meaning |
|---|---|
| Middleware | A func(http.Handler) http.Handler that wraps the next handler |
http.Handler | Interface with ServeHTTP(ResponseWriter, *Request) |
http.HandlerFunc | Adapter turning a function into a Handler |
| Chaining | Wrapping middlewares inside each other |
| Chain helper | Function composing middlewares in reading order |
| Ordering | The position of each middleware in the stack, which decides what it sees |
| Short-circuit | Answering without calling next |
| Route group | A chain applied to a subset of routes |
| Request ID | Per-request identifier in context, logs and X-Request-Id |
| Status capture | Recording the status code by wrapping ResponseWriter |
http.ResponseController | Go 1.20 type reaching Flush, Hijack, deadlines through Unwrap |
Unwrap | Method returning the wrapped ResponseWriter |
http.ErrNotSupported | Error when no writer in the chain supports a feature |
| Recover middleware | Deferred recover turning panics into logged 500s |
http.ErrAbortHandler | Sentinel panic value to abort a response without a logged stack |
| Timeout middleware | Puts a deadline on the request context |
http.TimeoutHandler | Stdlib wrapper answering 503 after a limit, buffering output |
| Content-Security-Policy | Header allowlisting content sources; frame-ancestors controls framing |
| Strict-Transport-Security (HSTS) | Header forcing HTTPS for max-age seconds |
| X-Content-Type-Options | nosniff: no MIME sniffing |
| X-Frame-Options | Legacy anti-framing header (DENY, SAMEORIGIN) |
| Referrer-Policy | How much URL the Referer header carries |
| Permissions-Policy | Switches browser features (camera, geolocation) on or off |
| CORS | Cross-Origin Resource Sharing: server opt-in for cross-origin reads |
| Origin | Request header with the caller page's scheme, host, port |
| Preflight | OPTIONS request with Access-Control-Request-Method sent before non-simple requests |
Access-Control-Allow-* | Response headers granting origin, methods, headers, credentials |
| Credentials | Cookies, HTTP auth, client certificates in a cross-origin request |
Vary | Response header naming request headers the response depends on |
| rs/cors | github.com/rs/cors, the common Go CORS middleware |
| Compression | Encoding the body (gzip) when the client accepts it |
| Accept-Encoding / Content-Encoding | Client's accepted encodings / encoding actually applied |
| BREACH | Compression side-channel recovering secrets from compressed HTTPS responses |
| X-Forwarded-For | Header listing client and proxy IPs, appended per hop |
| Trusted proxy | A proxy whose CIDR you configured; only its additions are believed |
| Token bucket | Bucket of b tokens refilled at r per second; each request takes one |
x/time/rate | golang.org/x/time/rate, Go's token-bucket limiter |
| 429 Too Many Requests | Status for rate limiting (RFC 6585) |
| Retry-After | Header telling the client when to retry |
| Prometheus histogram | Bucketed latency metric for quantiles |
MaxBytesReader | Body reader failing with *MaxBytesError past a limit |
| 413 | Request Entity Too Large (RFC 9110: Content Too Large) |
| Principal | The authenticated caller stored in the context |
| Unexported context key | Package-private key type preventing collisions |
| CSRF | Cross-site request forgery: another site triggering a state change with the user's cookies |
http.CrossOriginProtection | Go 1.25 CSRF middleware using Sec-Fetch-Site and Origin |
Sec-Fetch-Site | Fetch Metadata header: same-origin, same-site, cross-site, none |
| Request coalescing | Serving identical concurrent requests from one backend call |
| singleflight | golang.org/x/sync/singleflight, duplicate call suppression |
httptest | Package with NewRequest, NewRecorder, NewServer for tests |
| chi | Router whose middleware uses the stdlib shape |
| gin | Framework with gin.HandlerFunc, c.Next(), c.Abort() |
| Laravel middleware | Class with handle($request, $next), registered in bootstrap/app.php |
| Terminable middleware | Laravel middleware whose terminate runs after the response is sent |
References
- Mat Ryer, "How I write HTTP services in Go after 13 years", Grafana Labs, 10 February 2024: https://grafana.com/blog/2024/02/09/how-i-write-http-services-in-go-after-13-years/
net/httpHandler,ErrAbortHandler,TimeoutHandler,MaxBytesHandler,Error: https://go.dev/src/net/http/server.gonet/httpResponseController: https://go.dev/src/net/http/responsecontroller.gonet/httpCrossOriginProtection: https://go.dev/src/net/http/csrf.gonet/httpMaxBytesReader,MaxBytesError,Request.Pattern,ErrNotSupported: https://go.dev/src/net/http/request.gonet/http/httptestResponseRecorder: https://go.dev/src/net/http/httptest/recorder.gonet/http/httputilReverseProxy: https://go.dev/src/net/http/httputil/reverseproxy.gonet/httpTransport.DisableCompression: https://go.dev/src/net/http/transport.golog/slogLogger: https://go.dev/src/log/slog/logger.gocompress/gzip: https://go.dev/src/compress/gzip/gzip.go- Go 1.18 release notes (
MaxBytesHandler): https://go.dev/doc/go1.18 - Go 1.19 release notes (
MaxBytesError): https://go.dev/doc/go1.19 - Go 1.20 release notes (
ResponseController): https://go.dev/doc/go1.20 - Go 1.21 release notes (
EnableFullDuplex): https://go.dev/doc/go1.21 - Go 1.22 release notes (enhanced routing patterns): https://go.dev/doc/go1.22
- Go 1.23 release notes (
Request.Pattern): https://go.dev/doc/go1.23 - Go 1.25 release notes (
CrossOriginProtection): https://go.dev/doc/go1.25 - "Routing Enhancements for Go 1.22", The Go Blog: https://go.dev/blog/routing-enhancements
- "Go Concurrency Patterns: Context", The Go Blog: https://go.dev/blog/context
golang.org/x/time/ratesource: https://raw.githubusercontent.com/golang/time/master/rate/rate.gogolang.org/x/sync/singleflightsource: https://raw.githubusercontent.com/golang/sync/master/singleflight/singleflight.go- rs/cors README: https://raw.githubusercontent.com/rs/cors/master/README.md
- go-chi/cors README: https://raw.githubusercontent.com/go-chi/cors/master/README.md
- chi
Chain: https://raw.githubusercontent.com/go-chi/chi/master/chain.go - chi
Recoverer: https://raw.githubusercontent.com/go-chi/chi/master/middleware/recoverer.go - chi
RealIP(deprecated): https://raw.githubusercontent.com/go-chi/chi/master/middleware/realip.go - chi
ClientIPFromXFF: https://raw.githubusercontent.com/go-chi/chi/master/middleware/client_ip.go - chi
Compress: https://raw.githubusercontent.com/go-chi/chi/master/middleware/compress.go - chi
RequestID: https://raw.githubusercontent.com/go-chi/chi/master/middleware/request_id.go - chi
Timeout: https://raw.githubusercontent.com/go-chi/chi/master/middleware/timeout.go - chi
Throttle: https://raw.githubusercontent.com/go-chi/chi/master/middleware/throttle.go - gin
Recovery: https://raw.githubusercontent.com/gin-gonic/gin/master/recovery.go - gin
Default: https://raw.githubusercontent.com/gin-gonic/gin/master/gin.go - gin
Context.Next,Abort: https://raw.githubusercontent.com/gin-gonic/gin/master/context.go - gin-contrib/cors README: https://raw.githubusercontent.com/gin-contrib/cors/master/README.md
- gin-contrib/requestid README: https://raw.githubusercontent.com/gin-contrib/requestid/master/README.md
- gin-contrib/gzip README: https://raw.githubusercontent.com/gin-contrib/gzip/master/README.md
- gin-contrib/timeout README: https://raw.githubusercontent.com/gin-contrib/timeout/master/README.md
- NGINX
limit_req: https://nginx.org/en/docs/http/ngx_http_limit_req_module.html - NGINX
proxy_cache_lock: https://nginx.org/en/docs/http/ngx_http_proxy_module.html - NGINX
set_real_ip_from,real_ip_recursive: https://nginx.org/en/docs/http/ngx_http_realip_module.html - AWS, Application Load Balancer request tracing (
X-Amzn-Trace-Id): https://docs.aws.amazon.com/elasticloadbalancing/latest/application/load-balancer-request-tracing.html - Prometheus
promhttpinstrumentation: https://raw.githubusercontent.com/prometheus/client_golang/main/prometheus/promhttp/instrument_server.go - Prometheus
DefBuckets: https://raw.githubusercontent.com/prometheus/client_golang/main/prometheus/histogram.go - Prometheus, "Histograms and summaries": https://prometheus.io/docs/practices/histograms/
- klauspost
gzhttpREADME (BREACH jitter): https://raw.githubusercontent.com/klauspost/compress/master/gzhttp/README.md - MDN, Cross-Origin Resource Sharing (CORS): https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CORS
- MDN,
Access-Control-Allow-Origin: https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Access-Control-Allow-Origin - MDN,
Access-Control-Allow-Credentials: https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Access-Control-Allow-Credentials - MDN,
Content-Security-Policy: https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Content-Security-Policy - MDN,
Strict-Transport-Security: https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Strict-Transport-Security - MDN,
X-Content-Type-Options: https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/X-Content-Type-Options - MDN,
X-Frame-Options: https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/X-Frame-Options - MDN,
Referrer-Policy: https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Referrer-Policy - MDN,
Permissions-Policy: https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Permissions-Policy - MDN,
Vary: https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Vary - MDN,
Content-Encoding: https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Content-Encoding - MDN,
Retry-After: https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Retry-After - MDN,
X-Forwarded-For: https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/X-Forwarded-For - MDN,
Sec-Fetch-Site: https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Sec-Fetch-Site - MDN, 429 Too Many Requests: https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/429
- OWASP Secure Headers Project: https://owasp.org/www-project-secure-headers/
- OWASP HTTP Headers Cheat Sheet: https://cheatsheetseries.owasp.org/cheatsheets/HTTP_Headers_Cheat_Sheet.html
- OWASP Cross-Site Request Forgery Prevention Cheat Sheet: https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html
- web.dev, "Protect your resources from web attacks with Fetch Metadata": https://web.dev/articles/fetch-metadata
- Fetch Standard (CORS protocol): https://fetch.spec.whatwg.org/
- Filippo Valsorda, on CSRF and
Sec-Fetch-Site: https://words.filippo.io/csrf/ - BREACH attack: https://www.breachattack.com/
- RFC 6585, Additional HTTP Status Codes (429): https://www.rfc-editor.org/rfc/rfc6585.html
- RFC 7239, Forwarded HTTP Extension: https://www.rfc-editor.org/rfc/rfc7239.html
- RFC 9110, HTTP Semantics (
Vary, content codings, 413): https://www.rfc-editor.org/rfc/rfc9110.html - Laravel 13, Middleware: https://laravel.com/docs/13.x/middleware
- Laravel 13, Routing (rate limiting, CORS): https://laravel.com/docs/13.x/routing
- Laravel 13, Requests (trusting proxies): https://laravel.com/docs/13.x/requests
- Laravel 13, Context (
Context::add): https://laravel.com/docs/13.x/context - Module
go.modfiles: https://proxy.golang.org/golang.org/x/time/@v/v0.15.0.mod and https://proxy.golang.org/github.com/prometheus/client_golang/@v/v1.24.1.mod - Laravel framework default
config/cors.php: https://raw.githubusercontent.com/laravel/framework/13.x/config/cors.php