Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Golang: io.Reader stream to string or byte slice
import "bytes"
func StreamToByte(stream io.Reader) []byte {
buf := new(bytes.Buffer)
buf.ReadFrom(stream)
return buf.Bytes()
}
func StreamToString(stream io.Reader) string {
buf := new(bytes.Buffer)
buf.ReadFrom(stream)
return buf.String()
}
@MheniMerz

This comment has been minimized.

Copy link

@MheniMerz MheniMerz commented Aug 3, 2017

thank you that was very useful, but the problem with this code is that it is usable only once, i.e: if you read once the next time you have an empty output.

@mayu899

This comment has been minimized.

Copy link

@mayu899 mayu899 commented Mar 22, 2019

Nice code, better do aN err check for ReadFrom.
usable only once is because the nature of the steam

@luillyfe

This comment has been minimized.

Copy link

@luillyfe luillyfe commented Dec 6, 2020

👍

@hybnew

This comment has been minimized.

Copy link

@hybnew hybnew commented Jan 13, 2021

nice

@amanbolat

This comment has been minimized.

Copy link

@amanbolat amanbolat commented May 29, 2021

io.Copy is much faster than using ReadFrom method.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment