Skip to content

Instantly share code, notes, and snippets.

@xeoncross
Created February 18, 2020 22:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xeoncross/312590d8562963bb0a7152de584d4f37 to your computer and use it in GitHub Desktop.
Save xeoncross/312590d8562963bb0a7152de584d4f37 to your computer and use it in GitHub Desktop.
Example of using os.Signal interrupts (or CTRL+C) to stop context which can be used to end a process, database query, or http server.
func InterruptContext() context.Context {
quit := make(chan os.Signal, 1)
signal.Notify(quit, os.Interrupt, syscall.SIGINT, syscall.SIGTERM)
ctx, cancel := context.WithCancel(context.Background())
go func() {
<-quit
cancel()
}()
return ctx
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment