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
| Option | Type | Default | Description |
|---|---|---|---|
Handler | func(*mizu.Ctx, int64) | nil | Size callback |
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:| Test Case | Description | Expected Behavior |
|---|---|---|
TestNew | Basic middleware creation | Middleware executes without errors and returns 200 OK |
TestWithOptions_Callback | OnSize callback functionality | Callback receives correct byte count (5 bytes for “12345”) |
TestBytesWritten | BytesWritten helper function | Returns accurate byte count matching response body length |
TestGet | Info retrieval from context | Get() returns valid Info instance from context |
TestWithCallback | WithCallback convenience function | Callback is invoked with correct size (3 bytes for “abc”) |
TestEmptyResponse | Empty response handling | Reports 0 bytes for 204 No Content responses |
TestMultipleWrites | Multiple Write() calls | Accumulates bytes across multiple writes (“firstsecondthird” = 16 bytes) |
Related Middlewares
- requestsize - Request size tracking
- compress - Response compression
- metrics - Metrics collection