Skip to content

Commit 8bea1e9

Browse files
committed
refactor(signals): replace stop channel with signal context
1 parent 4ef074e commit 8bea1e9

File tree

1 file changed

+26
-17
lines changed

1 file changed

+26
-17
lines changed

pkg/lib/signals/signals.go

Lines changed: 26 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,38 @@
11
package signals
22

33
import (
4+
"context"
45
"os"
56
"os/signal"
7+
"sync"
68
"syscall"
79
)
810

9-
var shutdownSignals = []os.Signal{os.Interrupt, syscall.SIGTERM}
10-
var onlyOneSignalHandler = make(chan struct{})
11+
var (
12+
shutdownSignals = []os.Signal{os.Interrupt, syscall.SIGTERM}
13+
signalCtx context.Context
14+
cancel context.CancelFunc
15+
once sync.Once
16+
)
1117

12-
// SetupSignalHandler registered for SIGTERM and SIGINT. A stop channel is returned
13-
// which is closed on one of these signals. If a second signal is caught, the program
14-
// is terminated with exit code 1.
15-
func SetupSignalHandler() (stopCh <-chan struct{}) {
16-
close(onlyOneSignalHandler) // panics when called twice
18+
// Context returns a Context registered to close on SIGTERM and SIGINT.
19+
// If a second signal is caught, the program is terminated with exit code 1.
20+
func Context() context.Context {
21+
once.Do(func() {
22+
c := make(chan os.Signal, 2)
23+
signal.Notify(c, shutdownSignals...)
24+
signalCtx, cancel = context.WithCancel(context.Background())
25+
go func() {
26+
<-c
27+
cancel()
1728

18-
stop := make(chan struct{})
19-
c := make(chan os.Signal, 2)
20-
signal.Notify(c, shutdownSignals...)
21-
go func() {
22-
<-c
23-
close(stop)
24-
<-c
25-
os.Exit(1) // second signal. Exit directly.
26-
}()
29+
select {
30+
case <-signalCtx.Done():
31+
case <-c:
32+
os.Exit(1) // second signal. Exit directly.
33+
}
34+
}()
35+
})
2736

28-
return stop
37+
return signalCtx
2938
}

0 commit comments

Comments
 (0)