HTTP Response Status Codes

· 180 words · 1 minute read

When making http requests with Go it is almost always necessary to check the status code of the response which is returned. Generally, if the status code is between 200 and 300 you can treat as successful. But anything except a 200-300 status, we often need to handle.

Go has many built methods to help us with this. For example, we can use http.StatusText() to convert the status code to it’s human readable name. Likewise, if we need to reference a http status code Go has constants for them, so we could say if resp.StatusCode == http.StatusNotFound.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package main

import (
    "fmt"
    "log"
    "net/http"
)

func main() {

    resp, err := http.Get("https://golangcode.com")
    if err != nil {
        log.Fatal(err)
    }

    // Print the HTTP Status Code and Status Name
    fmt.Println("HTTP Response Status:", resp.StatusCode, http.StatusText(resp.StatusCode))

    if resp.StatusCode >= 200 && resp.StatusCode <= 299 {
        fmt.Println("HTTP Status is in the 2xx range")
    } else {
        fmt.Println("Argh! Broken")
    }
}

Get the status code of a http request

Image of Author Edd Turtle

Author:  Edd Turtle

Edd is the Lead Developer at Hoowla, a prop-tech startup, where he spends much of his time working on production-ready Go and PHP code. He loves coding, but also enjoys cycling and camping in his spare time.

See something which isn't right? You can contribute to this page on GitHub or just let us know in the comments below - Thanks for reading!