HTTP client middleware via RoundTripper (headers + timing)

8345
0

When multiple services call the same upstream, I like a custom http.RoundTripper to centralize cross-cutting behavior: inject headers, measure duration, and apply consistent redaction rules. This keeps call sites clean and prevents copy/paste mistakes like forgetting to set User-Agent or missing an auth header for a new endpoint. The wrapper below adds an X-Request-Id and records a simple log line with duration; in real systems I’d record a Prometheus histogram and emit trace spans. The important design detail is to preserve the underlying transport so connection pooling still works; you wrap Transport, you don’t replace it with ad-hoc http.Clients. This pattern scales nicely as you add retries, rate limiting, and circuit breakers.