In Go, HTTP response bodies must be explicitly closed to prevent resource leaks. The Go documentation clearly states: "The caller must close the
response body when finished with it." When response bodies are not closed, several problems can occur:
- Connection pool exhaustion: The HTTP client maintains a pool of connections for reuse. If response bodies are not closed,
these connections cannot be returned to the pool, eventually exhausting available connections.
- Memory leaks: Unclosed response bodies can hold references to network resources and buffers, preventing garbage collection.
- Resource starvation: Over time, accumulated unclosed connections can consume system resources like file descriptors and
memory.
The issue is particularly problematic in high-throughput applications where many HTTP requests are made. Even if the response data is fully read,
the body must still be explicitly closed to signal that the connection can be reused.
What is the potential impact?
Failing to close HTTP response bodies can lead to:
- Application crashes due to connection pool exhaustion
- Performance degradation as new connections must be created instead of reusing existing ones
- Resource exhaustion on the system level, affecting other applications
- Intermittent failures that are difficult to debug in production environments