Is there a way in go to convert a []byte slice to an io.Reader?

12,857

Solution 1

Yes: bytes.NewBuffer

io.Reader Example:

http://play.golang.org/p/P0VbE8UFpC

package main

import (
    "bytes"
    "encoding/base64"
    "io"
    "os"
)

func main() {
    // A Buffer can turn a string or a []byte into an io.Reader.
    buf := bytes.NewBuffer([]byte("R29waGVycyBydWxlIQ=="))
    dec := base64.NewDecoder(base64.StdEncoding, buf)
    io.Copy(os.Stdout, dec)
}

Solution 2

You can use the NewReader in the bytes package:

in := bytes.NewReader(b []byte)

https://golang.org/pkg/bytes/#NewReader

Share:
12,857
betlor5
Author by

betlor5

Updated on June 04, 2022

Comments

  • betlor5
    betlor5 about 2 years


    I have just started with go and was wondering, if it is possible to convert an []byte slice to an io.Reader. The Otherway around is possible as shown in ioutil.ReadAll.
    If not is it possible to use code.google.com/p/go.net/html.Tokenizer somehow with a byte slice?

  • Fred Hors
    Fred Hors almost 4 years
    What's different from bytes.NewReader?
  • Fred Hors
    Fred Hors almost 4 years
    What's different from bytes.NewBuffer?
  • Matt Oestreich
    Matt Oestreich almost 4 years
    @FredHors I know it's been a while but I was also curious about this, so I looked into the source code. Taken from a comment in the source code // Unlike a Buffer, a Reader is read-only and supports seeking.. I suppose the question should be "what's your use case?"
  • Matt Oestreich
    Matt Oestreich almost 4 years
    (putting this here, too) I know it's been a while but I was also curious about this, so I looked into the source code. Taken from a comment in the source code // Unlike a Buffer, a Reader is read-only and supports seeking.. I suppose the question should be "what's your use case?"