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.

GoResilience

Code

snippet
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

FAQ

What does Drain Response Bodies For Reuse print when run?
Running the file directly is enough — expect labeled output lines such as `get:`.