Skip to content

Instantly share code, notes, and snippets.

@sponomarev
Created October 17, 2018 20:10
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 sponomarev/9948ff0048651d04122f7898fc8b08de to your computer and use it in GitHub Desktop.
Save sponomarev/9948ff0048651d04122f7898fc8b08de to your computer and use it in GitHub Desktop.
Context with Signal
package cmd
import (
"context"
"os"
"os/signal"
"syscall"
)
// ContextWithSignal creates a context canceled when SIGINT or SIGTERM are notified
func ContextWithSignal(ctx context.Context) context.Context {
newCtx, cancel := context.WithCancel(ctx)
signals := make(chan os.Signal)
signal.Notify(signals, syscall.SIGINT, syscall.SIGTERM)
go func() {
select {
case <-signals:
cancel()
}
}()
return newCtx
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment