Skip to content

Instantly share code, notes, and snippets.

Created July 15, 2022 17:50
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
Example io.Pipe
func main() {
r, w := io.Pipe()
ctx := context.Background()
ctx, cancel := context.WithTimeout(ctx, time.Second*10)
defer cancel()
wg := sync.WaitGroup{}
go func(ctx context.Context) {
tick := time.Tick(time.Second)
defer wg.Done()
for {
select {
case <-ctx.Done():
w.CloseWithError(fmt.Errorf("custom error for great justice"))
case t := <-tick:
fmt.Printf("tick! %v\n", t.Format(time.RFC3339))
_, err := fmt.Fprintf(w, "---%v---!", t.Format(time.RFC3339))
if err != nil {
fmt.Printf("unable to write to pipe writer: %v\n", err)
go func(ctx context.Context, r io.Reader) {
defer wg.Done()
for {
buf := make([]byte, 16)
// this doesn't return until either there's enough data ( 8 bytes )
n, err := r.Read(buf)
if err == io.EOF {
fmt.Printf("\n\nDone reading!\n\n")
if err != nil {
fmt.Printf("unable to read: %v\n", err)
fmt.Printf("Read %v bytes: '%s'\n", n, buf[:n])
time.Sleep(time.Second * 2)
}(ctx, r)
fmt.Printf("launched goroutines, waiting for output\n")
fmt.Printf("\n\nAll done!\n\n")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment