Convert byte array in io.read to golang

In my project, I have an array of bytes from the response to the request.

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 body for io.read , how do I convert? I tried newreader / writer but was not successful.

+44
go
Apr 20 '15 at 11:05
source share
2 answers

To get a type that implements io.Reader from the []byte fragment, you can use bytes.NewReader in bytes :

 r := bytes.NewReader(byteData) 

This will return a value of type bytes.Reader , which implements io.Reader (and io.ReadSeeker ).

Do not worry that they are not the same “type”. io.Reader is an interface and can be implemented with various types. To learn a little about interfaces in Go, read Effective Transition: Interfaces and Types .

+91
Apr 20 '15 at 12:04
source share

r: = strings (byteData)

It also works to rotate [] bytes in io.reader

-2
Sep 19 '17 at 17:15
source share



All Articles