Search code examples
iogobyte

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



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?


Solution

  • 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)
    }