Skip to content

Instantly share code, notes, and snippets.

@anyu
Last active August 6, 2021 20:20
Show Gist options
  • Save anyu/5a1ca2748a15aecb270b8642604db7ea to your computer and use it in GitHub Desktop.
Save anyu/5a1ca2748a15aecb270b8642604db7ea to your computer and use it in GitHub Desktop.
// Go1.16+'s signal.NotifyContext to concisely handle graceful shutdowns on OS interrupts.
// Simple example from original submitter: https://henvic.dev/posts/signal-notify-context/
func main() {
// Pass a context with a timeout to tell a blocking function that it
// should abandon its work after the timeout elapses.
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
defer stop()
select { // blocks until
case <-time.After(10 * time.Second):
fmt.Println("missed signal")
case <-ctx.Done():
stop()
fmt.Println("signal received")
}
}
// <Go1.16's approach
func main() {
ctx, cncl := context.WithCancel(context.Background())
defer cncl()
signals := make(chan os.Signal, 1) // channel to intercept OS cmds
signal.Notify(signals, os.Interrupt)
go func() {
select {
case <-signals:
cncl()
case <-ctx.Done():
}
}()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment