How to read http response body in golang?

by daisha.padberg , in category: Golang , 2 years ago

How to read http response body in golang?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by armani , 2 years ago

@daisha.padberg use ioutil.ReadAll() to read any HTTP response body in Golang, code as an example:


 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
package main

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

func main() {

   // GET request to server
   res, err := http.Get("https://devhubby.com/api/thread/latest")
   if err != nil {
      panic(err)
   }

   defer res.Body.Close()

   // read http response body
   body, err := ioutil.ReadAll(res.Body)
   if err != nil {
      panic(err)
   }

   // print http response body
   fmt.Println(string(body))
}

Member

by casper , a year ago

@daisha.padberg 

To read the HTTP response body in Go, you can use the Body field of the http.Response struct. Here's an example:

 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"
    "io/ioutil"
    "net/http"
)

func main() {
    resp, err := http.Get("https://example.com")
    if err != nil {
        fmt.Printf("Error: %v", err)
        return
    }
    defer resp.Body.Close()

    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        fmt.Printf("Error: %v", err)
        return
    }

    fmt.Println(string(body))
}


This code sends an HTTP GET request to example.com and reads the response body into a byte slice using the ReadAll function from the io/ioutil package. The response body is then converted to a string and printed to the console. The defer statement ensures that the response body is closed as soon as the function returns.