How To Convert A Byte Slice To io.Reader In Golang

In this article we are going to see how you can convert a byte slice to a io.Reader in Go (Golang). A byte slice is just a “dynamic” array (slice) of bytes in Go, which for example can represent any data in memory, like file contents, data sent across the network, etc… It might be useful to convert a byte slice into an io.Reader because the io.Reader allows us to compose it with other parts of our program and the Go standard library as it implements the Read method.

byte slice to io.Reader

Let’s see an example on how we can convert a byte slice into an io.Reader in Go

package main

import (
  "bytes"
  "log"
)

func main() {
  data := []byte("this is some data stored as a byte slice in Go Lang!")
  
  // convert byte slice to io.Reader
  reader := bytes.NewReader(data)
  
  // read only 4 byte from our io.Reader
  buf := make([]byte, 4)
  n, err := reader.Read(buf)
  if err != nil {
    log.Fatal(err)
  }
  log.Println(string(buf[:n]))
}

The expected output is the following

2009/11/10 23:00:00 this

Try running this by yourself on the Go Playground https://play.golang.org/p/pzTj9J8aJyL

io.Reader to byte slice

Let’s see an example on how we can now convert a io.Reader into a byte slice in Go

package main

import (
  "bytes"
  "log"
  "strings"
)

func main() {
  ioReaderData := strings.NewReader("this is some data stored as a byte slice in Go Lang!")
  
  // creates a bytes.Buffer and read from io.Reader
  buf := &bytes.Buffer{}
  buf.ReadFrom(ioReaderData)
  
  // retrieve a byte slice from bytes.Buffer
  data := buf.Bytes()
  
  // only read the first 4 bytes
  log.Println(string(data[:4]))
}

The expected output is the following

2009/11/10 23:00:00 this

Try running this by yourself on the Go Playground https://play.golang.org/p/TPVm7Y7XIus

Join the Golang Developers Community on Golang Cafe