Golang: the HTTP module for get requests

Making HTTP requests in Golang is pretty simple, I’ve included a code sample below.

Within the main function we define two new variables (resp and err). The HTTP get function returns the response; which is the response header and any errors that may occur.

We then handle the errors – if we find that an error is created, we print the error message and exit the program with exit code 1.

Next, we create an empty byte slice with 99,999 empty ‘slots’. This is because, although a slice can expand and contract in size, the read function we’re going to use later doesn’t have access to that functionality.

Next, we read the response body into the slice we just created. We then convert that to string and print it.

Option 2 to print the data is to use the io.Copy function. Here, the response body is printed to the stdout.