Overview
Therequestsize middleware tracks request sizes for monitoring, logging, and metrics collection.
Use it when you need:
- Monitor request sizes
- Collect bandwidth metrics
- Analyze traffic patterns
Installation
Quick Start
Configuration
Options
Examples
Track in Context
With Callback
Combined with Response Size
API Reference
Functions
Technical Details
The requestsize middleware tracks request sizes by wrapping the request body with a customio.ReadCloser implementation:
Architecture
- Context Storage: Size information is stored in the request context using a private context key
- Body Wrapping: The middleware wraps
http.Request.Bodywith atrackingBodystruct that counts bytes as they’re read - Deferred Callback: Size callbacks are executed via
deferto ensure they run after the request body is processed
Implementation Details
-
Info Structure: Contains two fields:
ContentLength: TheContent-Lengthheader value (may be -1 if not set)BytesRead: Actual bytes read from the request body during processing
-
Tracking Mechanism: The
trackingBodywrapper intercepts allRead()calls and accumulates the byte count -
Context Integration: Size info is attached to the request context and can be retrieved using the
Get(),ContentLength(), orBytesRead()helper functions -
Callback Execution: If configured, the
OnSizecallback is invoked after request processing completes, providing access to final byte counts
Best Practices
- Use for bandwidth monitoring
- Track alongside response sizes
- Set alerts for unusually large requests
- Combine with body limit for enforcement
Testing
The middleware includes comprehensive test coverage for various scenarios:Related Middlewares
- responsesize - Response size tracking
- bodylimit - Size enforcement
- metrics - Metrics collection