将字节切片转换为io.Reader。

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

Convert byte slice to io.Reader

问题

在我的项目中,我有一个来自请求响应的字节切片。

defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
    log.Println("StatusCode为" + strconv.Itoa(resp.StatusCode))
    return
}

respByte, err := ioutil.ReadAll(resp.Body)
if err != nil {
    log.Println("读取响应数据失败")
    return
}

这段代码是有效的,但是如果我想要将响应的主体转换为io.Reader,该怎么做呢?我尝试使用newreader/writer,但没有成功。

英文:

In my project, I have a byte slice from a request's response.

defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
    log.Println("StatusCode为" + strconv.Itoa(resp.StatusCode))
    return
}

respByte, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Println("fail to read response data")
    return
}

This works, but if I want to get the response's body for io.Reader, how do I convert? I tried the newreader/writer but wasn't successful.

答案1

得分: 464

要从[]byte切片中获取一个实现了io.Reader接口的类型,你可以使用bytes.NewReader函数,该函数位于bytes包中:

r := bytes.NewReader(byteData)

这将返回一个类型为bytes.Reader的值,该类型实现了io.Reader(以及io.ReadSeeker)接口。

不用担心它们不是相同的“类型”。io.Reader是一个接口,可以由许多不同的类型来实现。要了解更多关于Go中接口的知识,请阅读Effective Go: Interfaces and Types

英文:

To get a type that implements io.Reader from a []byte slice, you can use bytes.NewReader in the bytes package:

r := bytes.NewReader(byteData)

This will return a value of type bytes.Reader which implements the io.Reader (and io.ReadSeeker) interface.

Don't worry about them not being the same "type". io.Reader is an interface and can be implemented by many different types. To learn a little bit more about interfaces in Go, read Effective Go: Interfaces and Types.

答案2

得分: 0

创建一个缓冲区也可以这样实现:

r := bytes.NewBuffer(byteData)
英文:

Create a buffer also works:

r := bytes.NewBuffer(byteData)

huangapple
  • 本文由 发表于 2015年4月20日 19:05:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/29746123.html
匿名

发表评论

匿名网友

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

确定