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.
packagemainimport("log""net/http""net/http/httptrace")funcmain(){// 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.
funcMakeHttpCall()error{req,err:=http.NewRequest(http.MethodGet,"https://gophercoding.com",nil)iferr!=nil{returnerr}clientTrace:=&httptrace.ClientTrace{GotConn:func(infohttptrace.GotConnInfo){log.Printf("Connection was reused: %t",info.Reused)},DNSDone:func(dnsInfohttptrace.DNSDoneInfo){log.Printf("DNS Info: %+v\n",dnsInfo)},}req=req.WithContext(httptrace.WithClientTrace(req.Context(),clientTrace))_,err=http.DefaultTransport.RoundTrip(req)returnerr}
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.
For more information on httptrace checkout their docs.
Edd is a PHP and Go developer who enjoys blogging about his experiences, mostly about creating and coding new things he's working on and is a big beliver in open-source and Linux.