Capture HTTP Status Codes in Go Middleware With a ResponseWriter Wrapper
Write composable func(http.Handler) http.Handler middleware, embed http.ResponseWriter to record status codes, and return early on auth failures. After this, access logging and auth stay outside route handlers.
Every production API needs request logging that records HTTP status codes (200, 404, 500) and latency. Yet when you write your first Go logging middleware, you hit a surprising wall: http.ResponseWriter has no StatusCode() method.
Why? Because http.ResponseWriter is a minimal interface focused purely on writing headers and bytes—once a handler calls w.WriteHeader(404), that status is written directly to the HTTP response buffer without storing an exported getter on w. To log status codes cleanly in middleware, you wrap http.ResponseWriter in a small recorder struct.
Skip ahead
Jump straight to statusRecorder or preserving http.Flusher / Unwrap().
1. The statusRecorder wrapper (and the implicit 200 OK trap)
Watch out for two net/http subtleties when writing a wrapper:
- Implicit
200 OK: If a handler callsw.Write([]byte("ok"))without callingw.WriteHeaderfirst, Go implicitly sends200 OK. Initializestatus: http.StatusOKso empty or body-only responses never log status0! - Duplicate
WriteHeadercalls: Only the firstWriteHeadercall sets the wire status code; ignoring subsequent calls keeps your logged status accurate.
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))
}
$ go run .
GET /ok -> 200
GET /missing -> 404
2. Why Unwrap() matters for streaming and SSE
Handlers that stream Server-Sent Events or use http.NewResponseController(w).Flush() inspect w for optional interfaces like http.Flusher. Because our statusRecorder embeds http.ResponseWriter (which hides Flusher), adding Unwrap() http.ResponseWriter (supported in Go 1.20+) lets http.NewResponseController(w) reach the underlying server writer cleanly.
Middleware design rules
| Concern | Rule |
|---|---|
| Initial status | Always default to http.StatusOK (never 0) |
| Interface passthrough | Implement Unwrap() http.ResponseWriter |
| Middleware order | Put recoverMiddleware outside logMiddleware so panicked requests still log as 500 |
💡 Tip
Record start := time.Now() before next.ServeHTTP(rec, r) and log time.Since(start) alongside rec.status so slow endpoints stand out immediately in structured logs.
Common mistakes
- Forgetting to default
statusto200: Handlers that only callw.Write(...)end up logged as status0. - Swallowing
WriteHeaderwithout forwarding it: Always callsr.ResponseWriter.WriteHeader(code)so the client actually receives the status code. - Breaking
http.ResponseController: WithoutUnwrap(), streaming deadlines and flushes fail on wrapped writers.
⚠ Warning
Do not allocate a full response-body buffer inside statusRecorder.Write for every route—if a handler streams a 100 MB download, buffering it in middleware will OOM your server.
What happens if you skip this
Without a ResponseWriter wrapper, your access logs lose HTTP status codes completely—making it impossible to alert on 5xx spikes or debug 404/401 issues in production.
Related course: Go Intermediate.
About
Write composable func(http.Handler) http.Handler middleware, embed http.ResponseWriter to record status codes, and return early on auth failures. After this, access logging and auth stay outside route handlers.
- Responsible
- Jay P
- Last Update
- 11/27/2026
- Reading Time
- 4 min
Reviews
Sign in to write a reviewComments
Sign in to commentNo comments yet.