Skip to content

Instantly share code, notes, and snippets.

@chowey
Created June 8, 2017 02:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chowey/13a3cd9bfb5b988cfb4da05822c04f19 to your computer and use it in GitHub Desktop.
Save chowey/13a3cd9bfb5b988cfb4da05822c04f19 to your computer and use it in GitHub Desktop.
Like io.MultiReader, but using a channel (unknown number of input readers)
package main
import "io"
type channelReader struct {
c chan []byte
b []byte
}
func NewChannelReader(c chan []byte) io.Reader {
return &channelReader{c: c}
}
func (r *channelReader) Read(p []byte) (n int, err error) {
// drain buffer
if len(r.b) > 0 {
n = copy(p, r.b)
r.b = r.b[n:]
return
}
// get next from channel
var ok bool
if r.b, ok = <-r.c; !ok {
err = io.EOF
return
}
return r.Read(p)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment