Skip to content

Instantly share code, notes, and snippets.

@nicl
Created May 25, 2022 14:08
Show Gist options
  • Save nicl/2b054bac790aeabf687ddad7614d0559 to your computer and use it in GitHub Desktop.
Save nicl/2b054bac790aeabf687ddad7614d0559 to your computer and use it in GitHub Desktop.
Example of channels, etc.
package main
import (
"context"
"fmt"
"math/rand"
"time"
)
// Pretend we are finding tokens from the db and stream them over a channel.
func getTargets(ctx context.Context, out chan<- string) {
for i := 0; ; i++ {
select {
case <-ctx.Done():
fmt.Println("Cancelling getTargets...")
return
case out <- fmt.Sprintf("target %d", i):
time.Sleep(time.Second * 1)
}
}
}
// Pretend to process them by sending to e.g. Firebase
func processTargets(ctx context.Context, targets <-chan string, errorChan chan<- error) {
for target := range targets {
select {
case <-ctx.Done():
fmt.Println("Cancelling processTargets...")
return
default:
fmt.Printf("processing %s\n", target)
if rand.Float64() < 0.2 {
fmt.Printf("simulating error for %s\n", target)
errorChan <- fmt.Errorf("error for %s", target)
}
}
}
}
// Pretend to process errors
func handleErrors(ctx context.Context, errs <-chan error) {
for err := range errs {
select {
case <-ctx.Done():
fmt.Println("Cancelling handleErrors...")
return
default:
fmt.Printf("handling %v\n", err)
}
}
return
}
func main() {
ctx, cancel := context.WithCancel(context.Background())
errChan := make(chan error, 1)
targetChan := make(chan string, 1)
go getTargets(ctx, targetChan)
go processTargets(ctx, targetChan, errChan)
go handleErrors(ctx, errChan)
time.Sleep(time.Second * 10)
cancel()
time.Sleep(time.Second * 2)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment