问题描述
defer resp.Body.Close()$在我的项目中,我有一个来自请求响应的字节数组。 b $ b如果resp.StatusCode!= http.StatusOK {
log.Println(StatusCode为+ strconv.Itoa(resp.StatusCode))
返回
}
respByte,err:= ioutil.ReadAll(resp.Body)
如果err!= nil {
log.Println(无法读取响应数据)
返回
}
这个方法可行,但如果我想获得 io.read
,我该如何转换?我尝试了newreader / writer,但没有成功。
获得一个实现 io .Reader
来自 []字节
切片,您可以使用在包:
r:= bytes.NewReader(byteData)
这将返回,它实现了(以及)接口。
不要担心它们不是相同的类型。 io.Reader
是一个接口,可以通过许多不同的类型实现。要详细了解Go中的接口,请阅读。
In my project, I have a byte array 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.read
, how do I convert? I tried the newreader/writer but wasn't successful.
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.
这篇关于在golang中将字节数组转换为io.read的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!