将字节片转换为io.Reader [英] Convert byte slice to io.Reader

查看:123
本文介绍了将字节片转换为io.Reader的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的项目中,我从请求的响应中得到了一个字节片.

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
}

这可行,但是如果我想获取io.Reader的响应正文,该如何转换?我尝试过使用新阅读器/编写器,但没有成功.

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.

推荐答案

要从[]byte切片中获取实现io.Reader的类型,可以使用 bytes 中>包裹:

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)

这将返回类型为 bytes.Reader 的值,该值将实现 io.Reader (和 io.ReadSeeker )界面.

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

不用担心它们不是相同的类型". io.Reader是一个接口,可以用许多不同的类型实现.要了解有关Go中接口的更多信息,请阅读有效的Go:接口和类型.

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.

这篇关于将字节片转换为io.Reader的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆