In-memory IO
The bytes
package offers common primitives to achieve streaming IO on blocks of bytes, stored in memory, represented by the bytes.Buffer
type. Since the bytes.Buffer
type implements both io.Reader
and io.Writer
interfaces it is a great option to stream data into or out of memory using streaming IO primitives.
The following snippet stores several string values in the byte.Buffer
variable, book
. Then the buffer is streamed to os.Stdout
:
func main() { var books bytes.Buffer books.WriteString("The Great Gatsby") books.WriteString("1984") books.WriteString("A Tale of Two Cities") books.WriteString("Les Miserables") books.WriteString("The Call of the Wild") books.WriteTo(os.Stdout) }
golang.fyi/ch10/bytesbuf0.go
The same example can easily be updated to stream the content to a regular file as shown in the following abbreviate code snippet:
func main() { var books bytes.Buffer books.WriteString...