将字节切片转换为io.Reader

Cha*_*son 146 go

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

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
}
Run Code Online (Sandbox Code Playgroud)

这有效,但如果我想获得响应的主体io.Reader,我该如何转换?我尝试了新的阅读器/编写器,但没有成功.

ANi*_*sus 247

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

r := bytes.NewReader(byteData)
Run Code Online (Sandbox Code Playgroud)

这将返回bytes.Reader实现io.Reader(和io.ReadSeeker)接口的类型值.

不要担心它们不是同一种"类型".io.Reader是一个接口,可以通过许多不同的类型实现.要了解有关Go中接口的更多信息,请阅读Effective Go:Interfaces and Types.

  • @byxor是的,你要找的是[`bytes.Buffer`](https://golang.org/pkg/bytes/#Buffer).在那里你创建一个实现`io.Writer`的缓冲区:`w:= bytes.NewBuffer(destination)`. (3认同)