Skip to content

Instantly share code, notes, and snippets.

@ankur22
Created May 8, 2020 19:53
Show Gist options
  • Save ankur22/7c3b3f108aba5ca73dec08f0e17c0cb8 to your computer and use it in GitHub Desktop.
Save ankur22/7c3b3f108aba5ca73dec08f0e17c0cb8 to your computer and use it in GitHub Desktop.
Using errgroup
eg, ctx := errgroup.WithContext(ctx)
eg.Go(func() error {
defer close(lines)
for {
if !scanner.Scan() {
fmt.Println("Reader: Completed")
break
}
lines <- scanner.Text()
select {
case <-ctx.Done():
fmt.Println("Reader: Context closed")
return ctx.Err()
default:
}
}
if err := scanner.Err(); err != nil {
return fmt.Errorf("reader error - %w", err)
}
return nil
})
eg.Go(func() error {
for {
select {
case <-ctx.Done():
fmt.Println("Sender: Context closed")
return ctx.Err()
case l, ok := <-lines:
if !ok {
fmt.Printf("Sender: Channel closed\n", l)
return nil
}
fmt.Printf("Sender: Sending %s to remote database\n", l)
}
}
})
err = eg.Wait()
if err != nil {
fmt.Printf("error from goroutine - %v\n", err)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment