How to convert an HTTP response body to a string in Go

This article describes how you can parse the response of a web request and access it as a string in Go.

It’s often necessary to inspect the contents of an HTTP response for debugging purposes. Simply use the ioutil.ReadAll() function to read the whole body into a slice of bytes and convert the byte slice to a string with the string() function:

package main

import (
	"fmt"
	"io/ioutil"
	"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()

	bytes, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Fatalln(err)
	}

	fmt.Println(string(bytes))
}
Output
{
  "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
}

If you want to print the entire response including the headers, or only the response headers (without the body), you may use the httputil.DumpResponse() method instead:

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()

	bytes, err := httputil.DumpResponse(resp, true)
	if err != nil {
		fmt.Println(err)
	}

	fmt.Println(string(bytes))
}
Output
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
}

To exclude the response body from the output (and print only the headers), change the boolean argument to httputil.DumpResponse from true to false. Note that a corresponding httputil.DumpRequest method exists that is just like DumpResponse, but for dumping HTTP requests instead.

Thanks for reading, and happy coding!