Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

golang
go
communitycreator

How to read the response body in Golang

Shubham Singh Kshatriya

In the previous shot, we learned how to make an HTTP GET request in Golang.

In this shot, we will learn how to read the body of the response. Before we do that, let’s see what a typical response looks like by making an HTTP GET request on this URL.

package main

import (
   "fmt"
   "net/http"
)

func main() {
   // make GET request
   response, error := http.Get("https://reqres.in/api/products")
   
   if error != nil {
      fmt.Println(error)
   }
   
   // print response
   fmt.Println(response)
}
Raw response of the GET request

As we can see in the code given above, the typical response of the GET request contains a large amount of incoherent data, like the header and the properties of the request.

Most of the time, the data that we may be interested in lies in the response body.

Reading the body of the response

To read the body of the response, we need to access its Body property first.

We can access the Body property of a response using the ioutil.ReadAll() method. This method returns a body and an error. When the error is nil, the body that is returned contains the data, and vice versa.

Note: The io/ioutil package provides I/O utility functions.

Syntax

body, error := ioutil.ReadAll(response.Body)

After reading data from the Body, we should close it in order to prevent a memory leak:

response.Body.Close()

Code in action

package main

import (
   "fmt"
   "net/http"
   "io/ioutil"
)

func main() {
   // make GET request
   response, error := http.Get("https://reqres.in/api/products")
   if error != nil {
      fmt.Println(error)
   }

   // read response body
   body, error := ioutil.ReadAll(response.Body)
   if error != nil {
      fmt.Println(error)
   }
   // close response body
   response.Body.Close()
   
   // print response body
   fmt.Println(string(body))
}
Reading the body of the response
  • Line 11: We make a GET request to this URL.

  • Line 17: If there are no errors, we use the ioutil.ReadAll() function to read the body of the response and store it in the body variable.

  • Line 22: After we read the body of the response, we close it.

  • Line 25: We stringify the data contained in the body variable and output it on the console.

RELATED TAGS

golang
go
communitycreator

CONTRIBUTOR

Shubham Singh Kshatriya
RELATED COURSES

View all Courses

Keep Exploring