繁体   English   中英

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

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


我刚开始使用go并且想知道,是否可以将[]字节切片转换为io.Reader。 如ioutil.ReadAll所示,可以使用其他方式。
如果不是可以使用code.google.com/p/go.net/html.Tokenizer以某种方式使用字节切片?

是的: bytes.NewBuffer

io.Reader示例:

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

您可以在bytes包中使用NewReader:

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

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

暂无
暂无

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

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