Practical Examples
Scenario 1: Simple HTTP Request Timeout
package main
import (
"fmt"
"io"
"net/http"
"time"
)
func simpleTimeout() {
client := &http.Client{
Timeout: 5 * time.Second,
}
resp, err := client.Get("https://example.com")
if err != nil {
fmt.Println("Request failed:", err)
return
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
fmt.Println("Read error:", err)
return
}
fmt.Println(string(body))
}
Scenario 2: Comprehensive Timeout Configuration
func advancedTimeout() {
client := &http.Client{
Transport: &http.Transport{
DialContext: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
}).DialContext,
TLSHandshakeTimeout: 10 * time.Second,
ResponseHeaderTimeout: 10 * time.Second,
ExpectContinueTimeout: 5 * time.Second,
},
Timeout: 45 * time.Second,
}
req, err := http.NewRequest("GET", "https://api.example.com/data", nil)
if err != nil {
fmt.Println("Request creation error:", err)
return
}
resp, err := client.Do(req)
if err != nil {
if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
fmt.Println("Request timed out")
}
return
}
defer resp.Body.Close()
}
Timeout Scenario Comparison
graph TD
A[Timeout Scenarios] --> B[Simple Timeout]
A --> C[Advanced Timeout]
B --> D[Single Timeout Value]
C --> E[Multiple Timeout Configurations]
Practical Timeout Strategies
Scenario |
Timeout Strategy |
Recommended Use |
Simple Web Requests |
Fixed Total Timeout |
Basic API calls |
Complex API Interactions |
Granular Timeouts |
Microservices, External APIs |
Performance-Critical Apps |
Custom Transport Config |
High-performance systems |
Error Handling Techniques
func robustTimeoutHandling() {
client := &http.Client{
Timeout: 10 * time.Second,
}
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
req, _ := http.NewRequestWithContext(ctx, "GET", "https://example.com", nil)
resp, err := client.Do(req)
switch {
case err == nil:
// Successful request
defer resp.Body.Close()
case context.DeadlineExceeded == ctx.Err():
fmt.Println("Request timed out")
default:
fmt.Println("Other error occurred:", err)
}
}
At LabEx, we recommend testing and adapting timeout configurations based on specific application requirements and network conditions.