Fix Unclosed HTTP Bodies & Missing Client Timeouts in Go
Why http.DefaultClient hangs forever and unclosed resp.Body leaks sockets, plus the 5-line production fix.
By the end of this tutorial you will know:
- Why
http.Get()andhttp.DefaultClienthave no timeout by default - Why forgetting
defer resp.Body.Close()leaks TCP sockets - How to configure a reusable
&http.Client{Timeout: ...}safely
Prerequisites: Go 1.20+ installed.
1. The big idea
Two small defaults in Go's net/http catch almost everyone at least once:
http.DefaultClienthasTimeout: 0, which means wait forever. If an upstream API hangs, your goroutine hangs with it.- Every successful HTTP response holds an open network stream in
resp.Body. If you do not close it, Go cannot reuse the TCP connection, and your server eventually runs out of file descriptors.
2. The buggy shortcut
// Two bugs in two lines:
resp, err := http.Get("https://api.example.com/health") // no timeout!
// Missing: if err != nil { ... } and defer resp.Body.Close()If you put defer resp.Body.Close() before checking err != nil, a failed request where resp is nil will panic!
3. The fix: custom http.Client + defer resp.Body.Close()
Create one shared *http.Client with an explicit Timeout, check err != nil first, and only then defer resp.Body.Close().
package main
import (
"fmt"
"io"
"net/http"
"time"
)
var httpClient = &http.Client{
Timeout: 10 * time.Second,
}
func fetchStatus(url string) (int, error) {
resp, err := httpClient.Get(url)
if err != nil {
return 0, err
}
defer resp.Body.Close()
// Drain small bodies so the underlying TCP connection can be reused.
_, _ = io.Copy(io.Discard, resp.Body)
return resp.StatusCode, nil
}
func main() {
code, err := fetchStatus("https://example.com")
if err != nil {
fmt.Println("Request failed:", err)
return
}
fmt.Println("Status:", code)
}Check your own Go code for http.Get( or http.DefaultClient. Replace them with a package-level &http.Client{Timeout: 10 * time.Second} and verify defer resp.Body.Close() always sits right after if err != nil.
4. Common pitfalls
| Mistake | Symptom | Fix |
|---|---|---|
defer resp.Body.Close() before if err != nil | Nil pointer panic on network failure | Always check if err != nil first |
Using http.Get in production | Goroutines hang forever on slow servers | Use a custom &http.Client{Timeout: ...} |
Creating a new http.Client per request | Socket/port exhaustion | Reuse a single http.Client instance |
5. What you learned
You now know why http.DefaultClient is unsafe for production services and how a shared http.Client with a timeout and proper resp.Body.Close() keeps connections healthy.
Video walkthrough
YouTubeClick play to load video (YouTube)