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.
Download a File from a URL
This post shows you how to download a file in Go from the internet to your computer. We use the standard lib http.Get() and io.Copy() functions to help us with it. This function should be efficient as it will stream the data into the file, as aposed to downloading it all into memory, then to file. We also show an alternative below if you want to take the filename from the URL.
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.