Convert an io.ReadCloser to String

Using Go, we often make HTTP calls these days using net/http, which result in a response of type io.ReadCloser… which are hard to read for the layman (like me). What we really want to the response in the form of a string which we can read. This post will talk about how to convert these ReadCloser into strings.

First we’ll look at the problem, then we have two different solutions.

Problem:

Because ReadCloser is a struct object, we can’t print it out using fmt/log.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
package main

import (
    "fmt"
    "net/http"
)

func main() {
    response, _ := http.Get("https://gophercoding.com/site.webmanifest")
    fmt.Println(response.Body)
}
1
2
$ go run ioread.go 
&{[] {0xc000096300} <nil> <nil>}

Solution 1: Buffer

Write the contents of the ReadCloser to an in-memory buffer.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
package main

import (
    "fmt"
    "net/http"
    "bytes"
)

func main() {
    response, _ := http.Get("https://gophercoding.com/site.webmanifest")

    buf := new(bytes.Buffer)
    buf.ReadFrom(response.Body)
    respBytes := buf.String()

    respString := string(respBytes)

    fmt.Printf(respString)
}

Solution 2: Ioutil

Use the helper package ioutil to read all the contents into a []byte array for us.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
package main

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

func main() {
    response, _ := http.Get("https://gophercoding.com/site.webmanifest")

    respBytes, err := ioutil.ReadAll(response.Body)
    if err != nil {
        panic(err)
    }

    respString := string(respBytes)

    fmt.Printf(respString)
}

how to read io.readcloser as string