Last active
March 10, 2022 05:23
-
-
Save matryer/3aa1040a088ebcdb76bda29a61ac0db3 to your computer and use it in GitHub Desktop.
Making Ctrl+C termination cancel the context.Context
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
func main() { | |
ctx := context.Background() | |
// trap Ctrl+C and call cancel on the context | |
ctx, cancel := context.WithCancel(ctx) | |
c := make(chan os.Signal, 1) | |
signal.Notify(c, os.Interrupt) | |
defer func() { | |
signal.Stop(c) | |
cancel() | |
}() | |
go func() { | |
select { | |
case <-c: | |
cancel() | |
case <-ctx.Done(): | |
} | |
}() | |
doSomethingAwesome(ctx) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment