Created
May 20, 2017 12:21
-
-
Save matejb/87064825093c42c1e76e7175665d9a9b to your computer and use it in GitHub Desktop.
Golang context with cancellation on signal receive
This file contains 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
func contextWithSigterm(ctx context.Context) context.Context { | |
ctxWithCancel, cancel := context.WithCancel(ctx) | |
go func() { | |
defer cancel() | |
signalCh := make(chan os.Signal, 1) | |
signal.Notify(signalCh, os.Interrupt, syscall.SIGTERM) | |
select { | |
case <-signalCh: | |
case <-ctx.Done(): | |
} | |
}() | |
return ctxWithCancel | |
} |
You’re welcome!
LOL 😅
@henvic could you please extend the example in your article?
The problem is that the os.Interrupt
is an alias to syscall.SIGINT
but at least on Linux we also must handle the SIGTERM
:
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
I had a problem when the systemd service stuck during reloading.
@stokito, thank you for the feedback. I've updated it.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@stokito Exactly, here's an example taken from https://henvic.dev/posts/signal-notify-context/. Thanks @henvic!