How to get the Response status code in Golang?


Response status codes are the numbers that we get in response that signify what type of response we received from the server when we asked for something from it.

There are different status codes that one gets from the response, and these are mainly divided into five categories.

Generally, the status codes are divided into these five classes.

  • 1xx (Informational)

  • 2xx (Successful)

  • 3xx (Redirection)

  • 4xx (Client Error)

  • 5xx (Server Error)

In this article, we will try to get two or more of these status codes.

Example 1

Let's start with a basic HTTP request to the google.com URL. Once we do that, we will get the response from the server and that response will contain the status code.

Consider the code shown below.

package main

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

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

   fmt.Println("The status code we got is:", resp.StatusCode)
}

Output

If we run the command go run main.go on the above code, then we will get the following output in the terminal.

The status code we got is: 200

Example 2

Each status code also holds a StatusText with itself, which we can also print with the statusCode.

Consider the code shown below.

package main

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

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

   fmt.Println("The status code we got is:", resp.StatusCode)
   fmt.Println("The status code text we got is:", http.StatusText(resp.StatusCode))
}

Output

If we run the command go run main.go on the above code, then we will get the following output in the terminal.

The status code we got is: 200
The status code text we got is: OK

Example 3

We were able to get the status code 200, as the URL was available at the moment. In case we make a request to a URL which isn't active, we will get a 404 status code.

Consider the code shown below.

package main

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

func main() {
   resp, err := http.Get("https://www.google.com/apple")
   if err != nil {
      log.Fatal(err)
   }

   fmt.Println("The status code we got is:", resp.StatusCode)
   fmt.Println("The status code text we got is:", http.StatusText(resp.StatusCode))
}

Output

If we run the command go run main.go on the above code, then we will get the following output in the terminal.

The status code we got is: 404
The status code text we got is: Not Found

Updated on: 01-Nov-2021

11K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements