Skip to main content

Overview

The keepalive 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 the Connection and Keep-Alive headers. The middleware follows a request-response flow:
  1. Configuration Initialization: Default values are set during middleware creation (60s timeout, 100 max requests)
  2. Request Processing: For each incoming request, the middleware:
    • Checks if keep-alive is disabled via DisableKeepAlive option
    • Inspects the client’s Connection header to detect if the client requested connection closure
    • Sets appropriate response headers based on configuration and client preferences
  3. Header Management: The middleware sets:
    • Connection: keep-alive to indicate persistent connection support
    • Keep-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: close header to gracefully close connections
  • Helper functions: Provides Disable(), WithTimeout(), and WithMax() for common configurations

Header Format

The Keep-Alive header uses the format: timeout={seconds}, max={requests} where:
  • timeout: Duration in seconds that the connection should remain open
  • max: 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

Testing

The keepalive middleware includes comprehensive test coverage: