英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论