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

huangapple go评论81阅读模式
英文:

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

问题

我刚刚开始学习Go语言,想知道是否可以将一个[]byte切片转换为io.Reader。反过来是可以的,可以使用ioutil.ReadAll进行转换。
如果不行,是否可以在一个byte切片上使用code.google.com/p/go.net/html.Tokenizer?

英文:

<br>
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.<br>
If not is it possible to use code.google.com/p/go.net/html.Tokenizer somehow with a byte slice?

答案1

得分: 12

是的,这是一个关于使用bytes.NewBufferio.Reader的示例代码。它的功能是将一个字符串或[]byte转换为io.Reader。代码中使用了base64包来解码经过base64编码的字符串,并将解码后的内容输出到标准输出。你可以在这个链接中查看完整的示例代码:http://play.golang.org/p/P0VbE8UFpC

英文:

Yes: bytes.NewBuffer

io.Reader Example:

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

package main

import (
	&quot;bytes&quot;
	&quot;encoding/base64&quot;
	&quot;io&quot;
	&quot;os&quot;
)

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

答案2

得分: 8

你可以使用bytes包中的NewReader函数:

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

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

英文:

You can use the NewReader in the bytes package:

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

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

huangapple
  • 本文由 发表于 2014年8月26日 09:37:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/25496752.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定