Readers/writers
Remember, Go uses a structural type system. This makes any data type that implements Read([]byte) (int,error)
an io.Reader
, and any data type that implements Write([]byte) (int,error)
an io.Writer
. There are many uses of this property in the standard library. In this recipe, we will look at some of the common uses of readers and writers.
Reading data from a reader
An io.Reader
fills a byte slice you pass to it. By passing a slice, you actually pass two pieces of information: how much you want to read (the length of the slice) and where to put the data that was read (the underlying array of the slice).
How to do it...
- Create a byte slice large enough to hold the data you want to read:
buffer := make([]byte,1024)
- Read the data into the byte slice:
nRead, err := reader.Read(buffer)
- Check how much was read. The number of bytes actually read may be smaller than the buffer size:
buffer = buffer[:nRead]
- Check the error. If the error is
io.EOF
, then the...