How to read the response body in Golang
package mainimport ("fmt""net/http")func main() {// make GET requestresponse, error := http.Get("https://reqres.in/api/products")if error != nil {fmt.Println(error)}// print responsefmt.Println(response)}
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/ioutilpackage 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 mainimport ("fmt""net/http""io/ioutil")func main() {// make GET requestresponse, error := http.Get("https://reqres.in/api/products")if error != nil {fmt.Println(error)}// read response bodybody, error := ioutil.ReadAll(response.Body)if error != nil {fmt.Println(error)}// close response bodyresponse.Body.Close()// print response bodyfmt.Println(string(body))}
-
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 thebodyvariable. -
Line 22: After we read the body of the response, we close it.
-
Line 25: We stringify the data contained in the
bodyvariable and output it on the console.