Convert byte slice to io.Reader

Go

Go Problem Overview


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.

Go Solutions


Solution 1 - Go

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.

Solution 2 - Go

r := strings(byteData)

This also works to turn []byte into io.Reader

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionChan WillsonView Question on Stackoverflow
Solution 1 - GoANisusView Answer on Stackoverflow
Solution 2 - GocmslotesView Answer on Stackoverflow