Overview
Theresponsesize middleware tracks response sizes for monitoring, logging, and metrics collection.
Use it when you need:
- Monitor response sizes
- Collect bandwidth metrics
- Detect response size anomalies
Installation
Quick Start
Configuration
Options
Examples
Track in Context
With Callback
Log Large Responses
API Reference
Functions
Technical Details
Implementation Architecture
The middleware uses a wrapping pattern to intercept and track response writes:-
Context Storage: Response size information is stored in the request context using a custom
contextKeytype for type-safe retrieval. -
Writer Wrapping: The middleware wraps the original
http.ResponseWriterwith atrackingWriterthat intercepts allWrite()calls. -
Atomic Tracking: Uses
sync/atomicoperations to safely track bytes written, ensuring thread-safe counting even with concurrent writes. -
Callback Mechanism: After the response is fully written, an optional callback (
OnSize) is invoked with the total byte count.
Key Components
- Info struct: Holds the
bytesWrittencounter with an atomic accessor methodBytesWritten(). - trackingWriter: A wrapper around
http.ResponseWriterthat increments the byte counter on each write. - contextKey: An empty struct used as a unique key for storing size info in the context.
Flow
- Create
Infoinstance and store in context - Wrap response writer with
trackingWriter - Execute next handler in chain
- Invoke
OnSizecallback with final byte count - Restore original writer
Best Practices
- Track alongside request sizes
- Set alerts for unusually large responses
- Use for bandwidth billing
- Monitor compression effectiveness
Testing
The middleware includes comprehensive test coverage:Related Middlewares
- requestsize - Request size tracking
- compress - Response compression
- metrics - Metrics collection