HTTP clients
Reuse clients, configure timeouts deliberately, and bind requests to context.
Canonical guidance
- reuse
http.Clientinstances - bind requests to context when request-scoped
- configure timeouts and transport behavior intentionally
- close response bodies promptly
Use when
- service-to-service HTTP
- external API integrations
- request-scoped outbound calls
Avoid
- creating a new client for every request
- no timeout strategy
- reading only part of a response and leaking the body
Preferred pattern
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return err
}
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
Anti-pattern
- default-zero client creation scattered across the codebase with no shared policy
Explanation: This anti-pattern is tempting in small helpers, but ad hoc clients and missing body cleanup quietly waste connections and increase latency.
Why
- outbound HTTP is a major source of latency and resource leaks in Go services
Related pages
Sources
- net/http package - Go Team
- Go Concurrency Patterns: Context - Sameer Ajmani