How to Convert an HTTP Response Body to a String in Go
To examine the contents of an HTTP response in Go, the io.ReadAll()
function
can be used to read the entire body into a byte slice, which is then converted
to a string with the string()
function.
The following example demonstrates this process:
package main
import (
"fmt"
"io"
"log"
"net/http"
)
func main() {
req, err := http.NewRequest("GET", "https://icanhazdadjoke.com", nil)
if err != nil {
log.Fatalln(err)
}
req.Header.Set("Accept", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
log.Fatalln(err)
}
defer resp.Body.Close()
b, err := io.ReadAll(resp.Body)
if err != nil {
log.Fatalln(err)
}
fmt.Println(string(b))
}
Here’s the expected output after executing the program above:
{
"id": "R7UfaahVfFd",
"joke": "My dog used to chase people on a bike a lot. It got so bad I had to take his bike away.",
"status": 200
}
To printing the entire response, including the headers, or just the headers
without the body, the httputil.DumpResponse()
method is useful:
package main
import (
"fmt"
"log"
"net/http"
"net/http/httputil"
)
func main() {
req, err := http.NewRequest("GET", "https://icanhazdadjoke.com", nil)
if err != nil {
log.Fatalln(err)
}
req.Header.Set("Accept", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
log.Fatalln(err)
}
defer resp.Body.Close()
b, err := httputil.DumpResponse(resp, true)
if err != nil {
log.Fatalln(err)
}
fmt.Println(string(b))
}
With the second argument of DumpResponse()
set to true
, the response body is
printed after the headers:
HTTP/2.0 200 OK
Cache-Control: max-age=0, must-revalidate, no-cache, no-store, public, s-maxage=0
Cf-Cache-Status: DYNAMIC
Cf-Ray: 5ad91d75bda5cd02-EWR
Cf-Request-Id: 03bb90bd950000cd02cb1dd200000001
Content-Type: application/json
Date: Sat, 04 Jul 2020 13:15:27 GMT
Expect-Ct: max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct"
Server: cloudflare
Set-Cookie: __cfduid=d032175648e90373f1271c27a0e5b55d71593868527; expires=Mon, 03-Aug-20 13:15:27 GMT; path=/; domain=.icanhazdadjoke.com; HttpOnly; SameSite=Lax
Strict-Transport-Security: max-age=15552000; includeSubDomains
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
X-Xss-Protection: 1; mode=block
{
"id":"NZDlb299Uf",
"joke":"Where do sheep go to get their hair cut? The baa-baa shop.",
"status":200
}
Thanks for reading, and happy coding!