在Golang中想要复用之前的TCP连接,必须要把上一个连接的Body读取完毕才能复用

检查工具:httptrace.ClientTrace
测试代码:

package main

import (
	"context"
	"io"
	"io/ioutil"
	"log"
	"net/http"
	"net/http/httptrace"
)

func main() {
	// client trace to log whether the request's underlying tcp connection was re-used
	clientTrace := &httptrace.ClientTrace{
		GotConn: func(info httptrace.GotConnInfo) { log.Printf("conn was reused: %t", info.Reused) },
	}

	traceCtx := httptrace.WithClientTrace(context.Background(), clientTrace)

	// 1st request
	req, err := http.NewRequestWithContext(traceCtx, http.MethodGet, "http://test.com/test.php", nil)
	if err != nil {
		log.Fatal(err)
	}
	res, err := http.DefaultClient.Do(req)
	if err != nil {
		log.Fatal(err)
	}
	defer res.Body.Close()
	if _, err := io.Copy(ioutil.Discard, res.Body); err != nil {
		log.Fatal(err)
	}	// 或者 ioutil.ReadAll(res.Body)
	
	// 2nd request
	req, err = http.NewRequestWithContext(traceCtx, http.MethodGet, "http://test.com/test.php", nil)
	if err != nil {
		log.Fatal(err)
	}
	_, err = http.DefaultClient.Do(req)
	if err != nil {
		log.Fatal(err)
	}
}

2022/01/21 10:10:12 conn was reused: false
2022/01/21 10:10:14 conn was reused: true