🚀 Get 25% off access to all my premium courses - use discount code FUNCMAIN at checkout - view the pricing page now!

Making HTTP requests in Go

Elliot Forbes Elliot Forbes ⏰ 3 Minutes 📅 Dec 16, 2022

Welcome Gophers! In this tutorial, we are going to be taking a quick look at how we can make HTTP requests in Go!

In Go, we can use the net/http package in order to help us make our own HTTP requests.

Importing the Package

To use the net/http package in your Go program, you will need to import it first:

import "net/http"

Making a GET Request

The most basic type of HTTP request is a GET request. To make a GET request, you can use the http.Get function like so:

resp, err := http.Get("http://www.example.com/")
if err != nil {
    // handle error
}
defer resp.Body.Close()

The http.Get function sends a GET request to the specified URL and returns a response object and an error. If there was an error making the request, the error will be non-nil.

The response object has a number of fields, including the status code, headers, and the response body. You can read the response body using the io.Reader interface:

body, err := io.ReadAll(resp.Body)
if err != nil {
    // handle error
}
fmt.Println(string(body))

The io.ReadAll function reads the entire response body into a byte slice. You can then convert the byte slice to a string and print it out.

Making a POST Request

Now that we’ve mastered the GET request, let’s take a look at other types of requests that we could be making.

To make a POST request, you can use the http.Post function:

resp, err := http.Post("http://www.example.com/post", "application/x-www-form-urlencoded", strings.NewReader("name=value"))
if err != nil {
    // handle error
}
defer resp.Body.Close()

The http.Post function takes three arguments: the URL, the content type of the request body, and the request body itself. In this example, we are sending a POST request with a form-encoded body.

Customizing the Request

To customize the HTTP request further, you can use the http.NewRequest function to create an *http.Request object:

req, err := http.NewRequest("GET", "http://www.example.com/", nil)
if err != nil {
    // handle error
}
req.Header.Set("User-Agent", "MyUserAgent/1.0")

The http.NewRequest function takes three arguments: the HTTP method, the URL, and the request body. In this example, we are creating a GET request with no request body.

You can then set headers on the request using the Header field of the *http.Request object. In this example, we are setting the User-Agent header.

To send the request, you can use the http.DefaultClient.Do function:

resp, err := http.DefaultClient.Do(req)
if err != nil {
    // handle error
}
defer resp.Body.Close()

The http.DefaultClient.Do function sends the request and returns a response.

That’s it! You now know how to make HTTP requests in Go.