简体   繁体   English

有没有办法将[]字节切换转换为io.Reader?

[英]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. 我刚开始使用go并且想知道,是否可以将[]字节切片转换为io.Reader。 The Otherway around is possible as shown in ioutil.ReadAll. 如ioutil.ReadAll所示,可以使用其他方式。
If not is it possible to use code.google.com/p/go.net/html.Tokenizer somehow with a byte slice? 如果不是可以使用code.google.com/p/go.net/html.Tokenizer以某种方式使用字节切片?

Yes: bytes.NewBuffer 是的: bytes.NewBuffer

io.Reader Example: io.Reader示例:

http://play.golang.org/p/P0VbE8UFpC 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)
}

You can use the NewReader in the bytes package: 您可以在bytes包中使用NewReader:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM