Timeout Configuration
HTTP Client Timeout Setup
In Golang, configuring HTTP timeouts involves customizing the http.Client
struct. This allows fine-grained control over different timeout parameters.
Basic Timeout Configuration
client := &http.Client{
Timeout: 10 * time.Second, // Global request timeout
}
Detailed Timeout Configuration
client := &http.Client{
Transport: &http.Transport{
DialContext: (&net.Dialer{
Timeout: 30 * time.Second, // Connection establishment timeout
KeepAlive: 30 * time.Second,
}).DialContext,
TLSHandshakeTimeout: 10 * time.Second, // TLS handshake timeout
ResponseHeaderTimeout: 10 * time.Second, // Response header timeout
ExpectContinueTimeout: 1 * time.Second,
MaxIdleConns: 100,
MaxIdleConnsPerHost: 10,
},
Timeout: 45 * time.Second, // Total request timeout
}
Timeout Configuration Strategies
Strategy |
Description |
Use Case |
Global Timeout |
Single timeout for entire request |
Simple scenarios |
Granular Timeout |
Multiple specific timeouts |
Complex network interactions |
Context-Based Timeout |
Cancellable requests |
Advanced request management |
Context-Based Timeout Example
graph TD
A[Create Context] --> B[Set Timeout]
B --> C[Make HTTP Request]
C --> D{Request Completed?}
D --> |Yes| E[Process Response]
D --> |No| F[Context Cancelled]
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
req, _ := http.NewRequestWithContext(ctx, "GET", "https://api.example.com", nil)
resp, err := client.Do(req)
Best Practices
- Always set timeouts explicitly
- Choose appropriate timeout durations
- Use context for more complex timeout scenarios
- Handle timeout errors gracefully
By mastering timeout configuration, LabEx developers can create more resilient and responsive network applications in Golang.