Skip to main content
  1. Tutorials/

📚 Convert byte slice to io.Reader in Go

·1 min

To convert a byte slice to io.Reader in Go, create a new bytes.Reader object using bytes.NewReader() function with the byte slice argument. The bytes.Reader type implements the io.Reader interface and can be used in any function that requires it as an argument.

package main

import (
    "bytes"
    "fmt"
    "log"
)

func main() {
    data := []byte("test byte slice")

    // byte slice to bytes.Reader, which implements the io.Reader interface
    reader := bytes.NewReader(data)

    // read the data from reader
    buf := make([]byte, len(data))
    if _, err := reader.Read(buf); err != nil {
        log.Fatal(err)
    }

    fmt.Println(string(buf))
}