Answers for "golang io.readcloser to string"

0

golang io.readcloser to string

package main

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

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

    // 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)
}
Posted by: Guest on June-06-2021

Browse Popular Code Answers by Language