Read twice from the same io.Reader

2,009 views
Skip to first unread message

michalis...@gmail.com

unread,
Apr 16, 2015, 8:08:04 AM4/16/15
to golan...@googlegroups.com
How can I do that? If I was reading from a file instead, I would probably run file.Seek(0,0) in between the reads, but how can this be done with io.Readers?

Dave Cheney

unread,
Apr 16, 2015, 8:14:50 AM4/16/15
to golan...@googlegroups.com
Type asset the value to see if it implements interface { Seek(int,int) error}. If it does not you will have to buffer the results from reading from the reader.

alessio....@gmail.com

unread,
Aug 7, 2015, 2:07:55 PM8/7/15
to golang-nuts
Can you provide sample code? 

Thanks

alexm

unread,
Aug 7, 2015, 2:58:04 PM8/7/15
to golang-nuts, alessio....@gmail.com
I coded up a simple example: http://play.golang.org/p/UA1wuGyCr3

You can see in the first part r implements the io.Seeker interface and so can be asserted as a Seeker in the function readAndPrint. On the other hand the buf doesn't implement the io.Seeker interface and will fail the condition check and you can see will only print just once. 

I hope this helped.

Alessio Cavaleri

unread,
Aug 8, 2015, 4:50:34 PM8/8/15
to alexm, golang-nuts
This solution works if you can assert that the io.Reader is also an io.Seeker, which is not always true. I've ended up to use a TeeReader, check this:https://gist.github.com/miku/293f253b706c4de1b75c
--
Alessio

Nick Craig-Wood

unread,
Aug 15, 2015, 1:06:09 PM8/15/15
to Alessio Cavaleri, alexm, golang-nuts
You are buffering the entire body in memory....

If you make the tee reader first, then run readFirst and readSecond as
go routines so they run at the same time you can get rid of the buffer.
> --
> You received this message because you are subscribed to the Google
> Groups "golang-nuts" group.
> To unsubscribe from this group and stop receiving emails from it, send
> an email to golang-nuts...@googlegroups.com
> <mailto:golang-nuts...@googlegroups.com>.
> For more options, visit https://groups.google.com/d/optout.


--
Nick Craig-Wood <ni...@craig-wood.com> -- http://www.craig-wood.com/nick
Reply all
Reply to author
Forward
0 new messages