Get Status Code from HTTP Request

We won’t go into too much detail about HTTP status codes themselves, but in this post we will talk about how to use the status code after making a request, how to check them as a range and how to print them as text. This is often important so we can check if something was successful or failed.

You can always get this data if you have a net/http/Response type (spec).

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package main

import (
    "fmt"
    "net/http"
)

func main() {

    // 1. Example of success - will print "Ok: 200"
    resp, err := http.Get("https://gophercoding.com")
    if err != nil {
        panic(err)
    }

    fmt.Printf("Ok: %d\n", resp.StatusCode)

    // 2. Missing page, check status code range
    resp, err = http.Get("https://gophercoding.com/missing.txt")
    if err != nil {
        panic(err)
    }

    if resp.StatusCode >= 200 && resp.StatusCode < 300 {
        fmt.Println("Page Found")
    } else {
        fmt.Println("Page Not Found")
    }

    // 3. Convert Status Code to Status Text e.g. "Not Found"
    fmt.Println(http.StatusText(resp.StatusCode))

}

http status code in golang

The last part of the example helps us turn a status code (so a number) into human readable text. This can be handy if you want to return something like “200 OK”, or “404 Not Found” dynamically.

We do this by calling http.StatusText()

1
http.StatusText(404)