Created
December 18, 2020 14:22
-
-
Save SkYNewZ/f0dd984f363346e770acb7d008be6a92 to your computer and use it in GitHub Desktop.
Simple Go file to understand context cancellation
This file contains hidden or 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
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