Check If a Go Client Has Reused a Connection

For logging purposes, performance monitoring, debugging - what ever your reason, it can be useful to know if Go has reused it’s connection when making an initial request, for later use. If it’s not reusing connections, it might be running slower and less efficiently than it needs to be.

The code below is used as an example of how to log if connections are being reused, as well as outputting the DNS information gathered.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package main

import (
	"log"
	"net/http"
	"net/http/httptrace"
)

func main() {

	// Call once, new connection is setup
	MakeHttpCall()

	// Call again, should reused the connection
	MakeHttpCall()
}

// MakeHttpCall is an example of making a http request, while logging any DNS info
// received and if the connection was established afresh, or re-used.
func MakeHttpCall() error {

	req, err := http.NewRequest(http.MethodGet, "https://gophercoding.com", nil)
	if err != nil {
		return err
	}

	clientTrace := &httptrace.ClientTrace{
		GotConn: func(info httptrace.GotConnInfo) {
			log.Printf("Connection was reused: %t", info.Reused)
		},
		DNSDone: func(dnsInfo httptrace.DNSDoneInfo) {
			log.Printf("DNS Info: %+v\n", dnsInfo)
		},
	}

	req = req.WithContext(httptrace.WithClientTrace(req.Context(), clientTrace))
	_, err = http.DefaultTransport.RoundTrip(req)
	return err
}

As you can see in the screenshot below, the DNS information is only gathered once because the connection is re-used for the second request.

To illustrate the point, we’ve also run the script twice. You can see that connections are not carried over when the script is next run.

check if go is reusing a http connection

For more information on httptrace checkout their docs.