github.com/hellofresh/janus@v0.0.0-20230925145208-ce8de8183c67/cmd/context.go (about) 1 package cmd 2 3 import ( 4 "context" 5 "os" 6 "os/signal" 7 "syscall" 8 ) 9 10 // ContextWithSignal create a context cancelled when SIGINT or SIGTERM are notified 11 func ContextWithSignal(ctx context.Context) context.Context { 12 newCtx, cancel := context.WithCancel(ctx) 13 signals := make(chan os.Signal) 14 signal.Notify(signals, syscall.SIGINT, syscall.SIGTERM) 15 go func() { 16 select { 17 case <-signals: 18 cancel() 19 close(signals) 20 } 21 }() 22 return newCtx 23 }