I'm currently available for contract work & technical writing opportunities. Hire me

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. In Go, you can use the io.ReadAll() function (or ioutil.ReadAll() in Go 1.15 and earlier) to read the whole body into a slice of bytes and convert the byte slice to a string with the string() function.

Here’s an example that shows this concept in action:

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)
	// b, err := ioutil.ReadAll(resp.Body)  Go.1.15 and earlier
	if err != nil {
		log.Fatalln(err)
	}

	fmt.Println(string(b))
}
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 just 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()

	b, err := httputil.DumpResponse(resp, true)
	if err != nil {
		log.Fatalln(err)
	}

	fmt.Println(string(b))
}
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, 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!