What is the best way in Go to skip forward a number of bytes in a stream using io.Reader
? That is, is there a function in the standard library which takes a reader and a count that will read and dispose count bytes from the reader?
Example use case:
func DoWithReader(r io.Reader) {
SkipNBytes(r, 30); // Read and dispose 30 bytes from reader
}
I don't need to go backwards in the stream so anything that can work without converting io.Reader
to another reader type would be preferred.
You could use this construction:
import "io"
import "io/ioutil"
io.CopyN(ioutil.Discard, yourReader, count)
It copies the requested amount of bytes into an io.Writer
that discards what it reads.
If your io.Reader
is an io.Seeker
, you might want to consider seeking in the stream to skip the amount of bytes you want to skip:
import "io"
import "io/ioutil"
switch r := yourReader.(type) {
case io.Seeker:
r.Seek(count, io.SeekCurrent)
default:
io.CopyN(ioutil.Discard, r, count)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With