Created
June 8, 2017 02:23
-
-
Save chowey/13a3cd9bfb5b988cfb4da05822c04f19 to your computer and use it in GitHub Desktop.
Like io.MultiReader, but using a channel (unknown number of input readers)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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