Skip to content

Instantly share code, notes, and snippets.

@spellgen
Last active March 26, 2021 23:03
Show Gist options
  • Save spellgen/aea75975ee87718b81e064fa96f9abf3 to your computer and use it in GitHub Desktop.
Save spellgen/aea75975ee87718b81e064fa96f9abf3 to your computer and use it in GitHub Desktop.
Clone reader with pipe + tee
package main
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"sync"
)
func main() {
r1 := bytes.NewBuffer([]byte("my data"))
pr, pw := io.Pipe()
tr := io.TeeReader(r1, pw)
var d1, d2 []byte
wg := new(sync.WaitGroup)
wg.Add(1)
// pick up the secondary stream in an independent go routine
go func() {
var err error
defer func() {
pw.Close()
wg.Done()
}()
d2, err = ioutil.ReadAll(tr)
if err != nil {
panic(err)
}
}()
// a read that would happen, possibly outside of our control
var err error
d1, err = ioutil.ReadAll(pr)
if err != nil {
panic(err)
}
wg.Wait()
fmt.Printf("d1=%s, d2=%s\n", d1, d2)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment