Golang Code

Convert io.ReadCloser to a String

· 97 words · 1 minute read #buffer #bytes #closer #get #io #read #string #readcloser #convert

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

package main

import (

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

	// This 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)
	newStr := buf.String()


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!