Skip to Content
Skip to content
Go Intermediate: Interfaces, Concurrency, and Services
Intermediate
Courses
Go Intermediate: Interfaces, Concurrency, and Services

Wrap HTTP Handlers With Middleware

Build composable func(http.Handler) http.Handler middleware and wrap http.ResponseWriter to record response status codes. After this, cross-cutting logging and headers stay out of handlers.

Course content

Sign in to save your progress.

Course Home

Once an HTTP service grows past five endpoints, repeating request logging, authentication checks, request-ID headers, or panic recovery inside every handler turns into copy-paste maintenance. Go's net/http solves cross-cutting logic with a single plain function signature—func(next http.Handler) http.Handler—requiring zero framework magic.

Skip ahead

If you already chain func(http.Handler) http.Handler wrappers, capture status codes with a ResponseWriter wrapper that defaults to 200 and implements Unwrap(), and know why middleware order matters, move on to "Build a Multi-Route Service With Graceful Shutdown."

Experiment 1: How middleware wraps http.Handler

Every middleware accepts the next handler and returns a new http.HandlerFunc that runs logic before calling next.ServeHTTP(w, r), after it returns, or short-circuits early (for example returning 401 Unauthorized without ever reaching the route handler):

func requireAPIKey(expected string, next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if r.Header.Get("X-API-Key") != expected {
			http.Error(w, "unauthorized", http.StatusUnauthorized)
			return // short-circuit: never call next.ServeHTTP
		}
		next.ServeHTTP(w, r)
	})
}
Diagram showing outer middleware wrapping inner middleware and the route handler
Incoming requests flow from outermost middleware inward; responses unwind back out.

Experiment 2: Capturing HTTP status codes without the "status 0" bug

When you write your first access-logging middleware, you quickly discover that http.ResponseWriter has no StatusCode() getter! Even trickier: if a handler calls w.Write([]byte("hello")) without calling w.WriteHeader first, Go implicitly sends 200 OK. A naive wrapper that leaves status at its zero value logs status 0 for every normal 200 response.

Initialize status: http.StatusOK, guard against duplicate WriteHeader calls, and implement Unwrap() so Go's http.ResponseController can still flush streaming responses:

package main

import (
	"fmt"
	"net/http"
	"net/http/httptest"
)

type statusRecorder struct {
	http.ResponseWriter
	status      int
	wroteHeader bool
}

func (sr *statusRecorder) WriteHeader(code int) {
	if !sr.wroteHeader {
		sr.status = code
		sr.wroteHeader = true
		sr.ResponseWriter.WriteHeader(code)
	}
}

func (sr *statusRecorder) Write(b []byte) (int, error) {
	if !sr.wroteHeader {
		sr.WriteHeader(http.StatusOK)
	}
	return sr.ResponseWriter.Write(b)
}

func (sr *statusRecorder) Unwrap() http.ResponseWriter {
	return sr.ResponseWriter
}

func logMiddleware(next http.Handler, logFn func(method, path string, status int)) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		rec := &statusRecorder{ResponseWriter: w, status: http.StatusOK}
		next.ServeHTTP(rec, r)
		logFn(r.Method, r.URL.Path, rec.status)
	})
}

func main() {
	mux := http.NewServeMux()
	mux.HandleFunc("GET /ok", func(w http.ResponseWriter, r *http.Request) {
		_, _ = w.Write([]byte("hello")) // no WriteHeader call!
	})
	mux.HandleFunc("GET /missing", func(w http.ResponseWriter, r *http.Request) {
		http.Error(w, "not found", http.StatusNotFound)
	})

	h := logMiddleware(mux, func(m, p string, s int) {
		fmt.Printf("%s %s -> %d\n", m, p, s)
	})

	h.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("GET", "/ok", nil))
	h.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("GET", "/missing", nil))
}
GET /ok -> 200
GET /missing -> 404

Experiment 3: Why middleware wrapping order matters

Think carefully about which wrapper goes on the outside when stacking three layers:

// Request path: recover -> logging -> auth -> mux
handler := recoverMiddleware(logMiddleware(authMiddleware(mux)))
  • recoverMiddleware outermost: Catches panics anywhere inside logging, auth, or handlers and turns them into a clean 500.
  • logMiddleware next: Logs every request—including 401 rejections from authMiddleware. (If you put authMiddleware outside logMiddleware, failed auth attempts disappear from your access logs!)
  • authMiddleware innermost: Rejects invalid callers before business handlers touch the database.

Common mistakes

  • Forgetting return after writing an error in auth/rate-limit middleware: Calls next.ServeHTTP anyway and runs the protected handler on an unauthorized request!
  • Omitting Unwrap() http.ResponseWriter on custom wrappers: Breaks http.NewResponseController(w).Flush() and per-route deadlines on streaming endpoints.
  • Buffering the entire response body in middleware just to log it: One 100 MB file download OOMs the server; log status code, latency, and byte count instead.

💡 Tip

Apply global middleware (recovery, logging) once around your root mux, and apply route-specific middleware (like requireAdmin) only to the sub-handlers that actually need it—leaving GET /health unauthenticated for Kubernetes probes.

What happens if you skip this step

Duplicating auth and logging across 30 handlers guarantees you eventually forget an auth check on one new route, and omitting status: http.StatusOK fills your production access logs with meaningless status 0 entries.

You wrap your router as authMiddleware(logMiddleware(mux)) instead of logMiddleware(authMiddleware(mux)). What happens to your access logs when someone sends 10,000 requests with an invalid API key?

About

Build composable func(http.Handler) http.Handler middleware and wrap http.ResponseWriter to record response status codes. After this, cross-cutting logging and headers stay out of handlers.

Duration
5 min
Last update
11/27/2026
Was this helpful?
​ 0 ​ 0

Comments

Sign in to comment

No comments yet.