package middleware
import "net/http"
type StatusRecorder struct {
http.ResponseWriter
Status int
Bytes int64
}
func (sr *StatusRecorder) WriteHeader(code int) {
sr.Status = code
sr.ResponseWriter.WriteHeader(code)
}
func (sr *StatusRecorder) Write(p []byte) (int, error) {
if sr.Status == 0 {
sr.Status = http.StatusOK
}
n, err := sr.ResponseWriter.Write(p)
sr.Bytes += int64(n)
return n, err
}
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.
Related snips
package api
import (
"net/http"
"runtime/debug"
)
Expose build metadata for debugging deploys
export interface RetryOptions {
retries: number;
baseMs: number;
maxMs: number;
signal?: AbortSignal;
onRetry?: (attempt: number, delay: number, err: unknown) => void;
Exponential backoff with jitter for retries
package dbutil
import (
"context"
"github.com/jackc/pgconn"
Retry Postgres serialization failures with bounded attempts
use tracing::{info, instrument};
#[instrument]
fn process_request(user_id: u64) {
info!(user_id, "Processing request");
// Work happens here
tracing for structured logging and distributed tracing
package files
import (
"context"
"time"
Presigned S3 upload URLs (AWS SDK v2)
package deps
import (
"net"
"net/http"
"time"
HTTP client tuned for production: timeouts, transport, and connection reuse
Share this code
Here's the card — post it anywhere.