Skip to content

Instantly share code, notes, and snippets.

@thearyanahmed
Last active June 16, 2021 19:10
Show Gist options
  • Save thearyanahmed/63c5242c72b0199ba32a243bc54baca5 to your computer and use it in GitHub Desktop.
Save thearyanahmed/63c5242c72b0199ba32a243bc54baca5 to your computer and use it in GitHub Desktop.
Enable double ctrl + c for cancel context in go
signalChan := make(chan os.Signal, 1)
signal.Notify(signalChan, os.Interrupt)
ctx := context.Background()
ctx, cancel := context.WithCancel(ctx)
go func() {
select {
case <-signalChan: // first signal, cancel context
cancel()
case <-ctx.Done():
}
<-signalChan // second signal, hard exit
os.Exit(1)
}()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment