Capture status code and bytes written via ResponseWriter wrapper

9693
0

When you need accurate request logs or metrics, you can’t rely on “what you intended to write” — you need what actually got written. Wrapping http.ResponseWriter to capture WriteHeader and count bytes is a simple way to record status codes and response sizes without changing every handler. This is also the foundation for middleware that emits access logs or Prometheus metrics. The key is correctness: default status should be 200 if WriteHeader is never called, and Write should ensure status is set before counting bytes. In production, I also capture duration, route name, and request ID. This keeps logging out of business logic and gives you consistent telemetry for debugging. It’s an old pattern, but it remains one of the most useful pieces of plumbing in Go HTTP servers.