Overview
Thetimeout middleware enforces a maximum duration for request processing. If a handler takes too long, the request is cancelled and an error response is returned.
Installation
Quick Start
Configuration
Examples
Basic Timeout
Custom Error Handler
Different Timeouts Per Route
Check Context in Handler
API Reference
How It Works
- Creates a context with deadline
- Runs handler in goroutine
- Returns whichever completes first:
- Handler completion
- Timeout expiration (returns 503)
Technical Details
Implementation
The timeout middleware uses Go’scontext.WithTimeout to enforce request deadlines:
- Context Creation: Creates a context with deadline using
context.WithTimeout(c.Context(), opts.Timeout) - Request Update: Replaces the request’s context with the timeout context
- Goroutine Execution: Runs the next handler in a separate goroutine to enable timeout detection
- Channel Communication: Uses a buffered channel to receive the handler’s result
- Select Statement: Races between handler completion and context cancellation
- If handler completes first, returns the result
- If timeout occurs first, calls error handler or returns 503 Service Unavailable
Default Values
- Timeout Duration: 30 seconds (when
Timeout <= 0) - Error Message: “Service Unavailable”
- HTTP Status: 503 Service Unavailable (when no custom error handler is provided)
Concurrency Safety
The middleware safely handles concurrent requests by:- Using a buffered channel (size 1) to prevent goroutine leaks
- Properly deferring the context cancel function to release resources
- Isolating each request’s timeout context
Best Practices
- Set reasonable timeouts based on expected duration
- Use longer timeouts for file uploads/downloads
- Check context in long-running operations
- Return 503 (Service Unavailable) on timeout
Testing
Test Cases
Related Middlewares
- recover - Panic recovery
- circuitbreaker - Failure handling