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.
Get/Set HTTP Headers in Go Request
–
HTTP headers, we all need ’em 😉
Here’s how you can get and set these headers within your Go requests. These include request coming into your router handlers and requests you are sending out to other systems through net/http. This can be thought of as being the same as reading headers from a request and creating new ones.
First we’ll start with reading them from the request.
Get Status Code from HTTP Request
–
We won’t go into too much detail about HTTP status codes themselves, but in this post we will talk about how to use the status code after making a request, how to check them as a range and how to print them as text. This is often important so we can check if something was successful or failed.
You can always get this data if you have a net/http/Response type (spec).
Convert an io.ReadCloser to String
–
Using Go, we often make HTTP calls these days using net/http, which result in a response of type io.ReadCloser… which are hard to read for the layman (like me). What we really want to the response in the form of a string which we can read. This post will talk about how to convert these ReadCloser into strings.
First we’ll look at the problem, then we have two different solutions.