Created
August 24, 2017 00:32
-
-
Save film42/b0dc3f0c8dff4ced94b63a44d727958f to your computer and use it in GitHub Desktop.
If you need to go from io.Reader to io.Reader but need to do a streaming io.Writer -> io.Reader before hand, this redirects the output
This file contains hidden or 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
type NoOpWriteCloser struct { | |
writer io.Writer | |
} | |
func (c *NoOpWriteCloser) Write(p []byte) (int, error) { | |
return c.writer.Write(p) | |
} | |
func (c *NoOpWriteCloser) Close() error { | |
return nil | |
} | |
type Redirect struct { | |
src io.Reader | |
srcEOF bool | |
redirect io.WriteCloser | |
dest io.Reader | |
} | |
func NewRedirect(src io.Reader, redirect io.WriteCloser, dest io.Reader) *Redirect { | |
var writeCloser io.WriteCloser | |
if wcloser, ok := redirect.(io.WriteCloser); ok { | |
writeCloser = wcloser | |
} else { | |
writeCloser = &NoOpWriteCloser{redirect} | |
} | |
return &Redirect{ | |
src: io.TeeReader(src, redirect), | |
srcEOF: false, | |
dest: dest, | |
redirect: writeCloser, | |
} | |
} | |
func (r *Redirect) Read(p []byte) (int, error) { | |
if !r.srcEOF { | |
_, err := r.src.Read(p) | |
if err == io.EOF { | |
r.srcEOF = true | |
r.redirect.Close() | |
} | |
} | |
return r.dest.Read(p) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment