Convert io.ReadCloser to a String

· 126 words · 1 minute read

Net/http is an amazing package but there are times you need to work with the body text of the response returned from the call you just made. Many functions require a string as input so we have to convert it first by passing it through a buffer.

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

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

func main() {
    response, _ := http.Get("/")

    // The line below would fail because Body = io.ReadCloser
    // fmt.Printf(response.Body)

    // ...so we convert it to a string by passing it through 
    // a buffer first. A 'costly' but useful process.
    buf := new(bytes.Buffer)
    buf.ReadFrom(response.Body)
    newStr := buf.String()

    fmt.Printf(newStr)
}

Image of Author Edd Turtle

Author:  Edd Turtle

Edd is the Lead Developer at Hoowla, a prop-tech startup, where he spends much of his time working on production-ready Go and PHP code. He loves coding, but also enjoys cycling and camping in his spare time.

See something which isn't right? You can contribute to this page on GitHub or just let us know in the comments below - Thanks for reading!