Go HTTP Client Timeout Not Working
In this tutorial, you'll learn about Go HTTP Client Timeout Not Working. We cover key concepts, practical examples, and best practices.
HTTP client timeouts -- Configure HTTP client timeouts correctly to prevent connections from hanging indefinitely and exhausting server resources.
The Problem
http.Client's Timeout field covers the entire request round-trip including body read, but it does not apply to individual steps. Connection pooling can cause requests to wait indefinitely for a free connection.
Wrong
client := &http.Client{}
resp, err := client.Get("https://api.example.com/data")
Output:
// Request hangs indefinitely if server is slow
// No goroutine will ever proceed
Right
client := &http.Client{
Timeout: 10 * time.Second,
Transport: &http.Transport{
DialContext: (&net.Dialer{Timeout: 5 * time.Second}).DialContext,
TLSHandshakeTimeout: 5 * time.Second,
ResponseHeaderTimeout: 5 * time.Second,
},
}
Output:
$ curl http://localhost:8080/proxy
// Returns within 10 seconds or fails fast
Prevention
- Set http.Client.Timeout for total request timeout
- Set transport-level timeouts (Dial, TLS handshake, response header)
- Use context.WithTimeout for per-call cancellation
- Set MaxIdleConns and MaxIdleConnsPerHost for connection pool control
- Always close response body: defer resp.Body.Close()
Common Mistakes with http client timeout
- Using
returnto exit a function early instead of wrapping a pure value in the monad - Mixing let bindings with <- bindings in do notation, producing type errors
- Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
These mistakes appear frequently in real-world GO code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro. DodaTech tutorials help Go developers build production-ready software used by millions.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro