[Go] Read an io.ReadCloser into a string

Created on November 30, 2026

Use io.ReadAll to read to EOF and convert the returned byte slice to a string. An io.ReadCloser implements io.Reader, so you can pass it directly to io.ReadAll.

package main

import (
    "fmt"
    "io"
    "strings"
)

func main() {
    reader := io.NopCloser(strings.NewReader("Hello, world!"))
    defer reader.Close()

    data, err := io.ReadAll(reader)
    if err != nil {
        panic(err)
    }

    fmt.Println(string(data))
}

Output

Hello, world!
Go