Created
May 8, 2020 19:53
-
-
Save ankur22/7c3b3f108aba5ca73dec08f0e17c0cb8 to your computer and use it in GitHub Desktop.
Using errgroup
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
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