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?
Asked
Active
Viewed 1.5k times
2 Answers
12
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)
}

fabrizioM
- 46,639
- 15
- 102
- 119
-
2What's different from `bytes.NewReader`? – Fred Hors Jul 03 '20 at 08:46
-
2@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](https://github.com/golang/go/blob/master/src/bytes/reader.go#L16) `// Unlike a Buffer, a Reader is read-only and supports seeking.`. I suppose the question should be "what's your use case?" – Matt Oestreich Sep 27 '20 at 23:11
8
You can use the NewReader in the bytes package:
in := bytes.NewReader(b []byte)

Fox32
- 13,126
- 9
- 50
- 71

Eurospoofer
- 614
- 10
- 7
-
1
-
1(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](https://github.com/golang/go/blob/master/src/bytes/reader.go#L16) // Unlike a Buffer, a Reader is read-only and supports seeking.. I suppose the question should be "what's your use case?" – Matt Oestreich Sep 27 '20 at 23:12