Skip to content

Instantly share code, notes, and snippets.

@SkYNewZ
Created December 18, 2020 14:22
Show Gist options
  • Save SkYNewZ/f0dd984f363346e770acb7d008be6a92 to your computer and use it in GitHub Desktop.
Save SkYNewZ/f0dd984f363346e770acb7d008be6a92 to your computer and use it in GitHub Desktop.
Simple Go file to understand context cancellation
package main
import (
"context"
"time"
log "github.com/sirupsen/logrus"
)
func main() {
ctx, cancel := context.WithTimeout(context.Background(), time.Second*2)
defer cancel()
if err := Close(ctx); err != nil {
log.Fatalln(err)
}
}
func long(done chan error) {
time.Sleep(time.Second * 5)
done <- nil
}
func Close(ctx context.Context) error {
done := make(chan error)
go long(done)
select {
case <-ctx.Done():
return ctx.Err()
case v := <-done:
return v
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment