Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go: Skip bytes from a stream using io.reader

Tags:

go

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.

like image 880
lmika Avatar asked Dec 02 '13 03:12

lmika


1 Answers

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)
}
like image 181
fuz Avatar answered Sep 21 '22 09:09

fuz