Created
October 17, 2018 20:10
-
-
Save sponomarev/9948ff0048651d04122f7898fc8b08de to your computer and use it in GitHub Desktop.
Context with Signal
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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