David Callanan
David Callanan

Reputation: 5970

Go check if bufio reader is empty

var r bufio.Reader

How do I check if r has no more data (is empty, is depleted)?

I understand that this may need to block until that information is known.

Can't find anything searching Google. I thought the Peek function would be useful to see if there is more data, but this seems to only peek an underlying buffer if exists. I could also try to Read one byte and subsequently call UnreadByte but that's extremely messy and unclear, are there any better options?

Upvotes: 1

Views: 3537

Answers (2)

Thundercat
Thundercat

Reputation: 121009

If r.Peek(1) returns data, then the next call to Read will return data.

If there's no data in the buffer, then Peek calls to the underlying reader and will block until data is available or an error.

Upvotes: 2

shmsr
shmsr

Reputation: 4204

If I understand your question correctly, would this work?

// func (*Reader) Size() int
// Size returns the size of the underlying buffer in bytes.
size := r.Size()

// func (*Reader) Buffered() int
// Buffered returns the number of bytes that can be read from the current buffer
buffered := r.Buffered()

Upvotes: 2

Related Questions