LESSON · 1 OF 23

Making a request with http.Get

Making a request with http.Get

A lot of DevOps work is talking to HTTP APIs - hitting a health check, reading a metrics endpoint, calling a cloud provider. Go has all of this in the standard library under net/http, so you do not need any third party package to get started.

The simplest way to fetch a URL is http.Get. It takes the URL as a string and returns two values, a response and an error:

go
resp, err := http.Get("http://example.com")
if err != nil {
    fmt.Println("request failed:", err)
    return
}

The error is not nil when the request could not even be made - the host did not resolve, the connection was refused, the request timed out. That is the usual if err != nil check you already know.

The shape to memorise: http.Get(url) gives you back (resp, err), and you check the error first.

Spin up a fresh environment and practice live.
go · fresh machine · ready in under a minute