Overview
Thekeepalive middleware controls HTTP keep-alive behavior, managing connection persistence for performance optimization.
Use it when you need:
- Connection persistence control
- Resource management
- Performance optimization
Installation
Quick Start
Configuration
Options
Examples
Enable Keep-Alive
Custom Settings
Disable Keep-Alive
Per-Route Control
API Reference
Functions
HTTP Headers
Technical Details
Implementation Overview
The keepalive middleware manages HTTP connection persistence by controlling theConnection and Keep-Alive headers. The middleware follows a request-response flow:
- Configuration Initialization: Default values are set during middleware creation (60s timeout, 100 max requests)
- Request Processing: For each incoming request, the middleware:
- Checks if keep-alive is disabled via
DisableKeepAliveoption - Inspects the client’s
Connectionheader to detect if the client requested connection closure - Sets appropriate response headers based on configuration and client preferences
- Checks if keep-alive is disabled via
- Header Management: The middleware sets:
Connection: keep-aliveto indicate persistent connection supportKeep-Alive: timeout={seconds}, max={requests}to specify connection parameters
Key Components
- Options struct: Configures timeout duration, maximum requests per connection, and enable/disable flag
- Default values: 60 seconds timeout, 100 maximum requests when not specified
- Client negotiation: Respects client’s
Connection: closeheader to gracefully close connections - Helper functions: Provides
Disable(),WithTimeout(), andWithMax()for common configurations
Header Format
TheKeep-Alive header uses the format: timeout={seconds}, max={requests} where:
timeout: Duration in seconds that the connection should remain openmax: Maximum number of requests allowed on this connection
Best Practices
- Use for high-traffic APIs
- Set reasonable timeouts
- Monitor connection counts
- Consider disabling for long-polling