Drain Response Bodies For Reuse
Copy unread response bodies to io.Discard before Close so keep-alive connections return to the pool and subsequent requests reuse them.
Code
package main
import (
"fmt"
"io"
"net/http"
"time"
)
func main() {
// 单个 Client 持有连接池:Transport 复用空闲连接
client := &http.Client{Timeout: 5 * time.Second}
for i := 0; i < 2; i++ {
resp, err := client.Get("https://example.com/")
if err != nil {
fmt.Println("get:", err)
return
}
// 不读 Body 也要排干(drain):连接才能回池被下一次请求复用
_, _ = io.Copy(io.Discard, resp.Body)
resp.Body.Close()
fmt.Println(i, "status:", resp.StatusCode)
}
}Under the hood
All the action sits in the function main — everything else is wiring.
Repetition is confined to for i := 0; i < 2; i++ — the rest of the file is straight-line. Error handling is inline: 1 place test err != nil and branch immediately.
Watch out for
- No dependency list exists — the runtime already supplies everything used here.
Applying it
What you call into: func main()
Output lines are prefixed (get:), so each printed line names the step that wrote it.
Statements that matter
if err != nil {
fmt.Println("get:", err)
return
}
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.HAR Waterfall AnalyzerInspect HTTP Archive (HAR 1.2) JSON files locally to summarize total requests, status codes, MIME types, slowest calls, and timing waterfalls.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.Accept Header ParserParse an Accept header into media ranges with their quality values and specificity, sorted by preference for content negotiation debugging.
FAQ
- What does Drain Response Bodies For Reuse print when run?
- Running the file directly is enough — expect labeled output lines such as `get:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.