在golang中将字节数组转换为io.read [英] Convert byte array to io.read in golang

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

问题描述

  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 来自 []字节切片,您可以使用 bytes.NewReader 字节 包:

  r:= bytes.NewReader(byteData)

这将返回 bytes.Reader ,它实现了 io.Reader (以及 io.ReadSeeker )接口。



不要担心它们不是相同的类型。 io.Reader 是一个接口,可以通过许多不同的类型实现。要详细了解Go中的接口,请阅读 Effective 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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