Skip to content

Instantly share code, notes, and snippets.

@hartfordfive
Forked from matryer/term_context.go
Created June 1, 2017 16:48
Show Gist options
  • Save hartfordfive/eaf83cd4c9de8ab5c77c5e5b94c2a1c3 to your computer and use it in GitHub Desktop.
Save hartfordfive/eaf83cd4c9de8ab5c77c5e5b94c2a1c3 to your computer and use it in GitHub Desktop.
Making Ctrl+C termination cancel the context.Context
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