I am aware of the specific function in golang from the bufio package.
func (b *Reader) Peek(n int) ([]byte, error)
Peek returns the next n bytes without advancing the reader. The bytes stop being valid at the next read call. If Peek returns fewer than n bytes, it also returns an error explaining why the read is short. The error is ErrBufferFull if n is larger than b's buffer size.
I need to be able to read a specific number of bytes from a Reader that will advance the reader. Basically, identical to the function above, but it advances the reader. Does anybody know how to accomplish this?
To do this you just need to create a byte slice and read the data into this slice with
func (b *Reader) Read(p []byte) (n int, err error)
Note that the
bufio.Read
method calls the underlyingio.Read
at most once, meaning that it can returnn < len(p)
, without reaching EOF. If you want to read exactlylen(p)
bytes or fail with an error, you can useio.ReadFull
like this:This works even if the reader is buffered.
I am prefering Read() especially if you are going to read any type of files and it could be also useful in sending data in chunks, below is an example to show how it is used
Pass a n-bytes sized buffer to the reader.
http://golang.org/pkg/bufio/#Reader.Read
The number of bytes read will be limited to
len(p)