-
Notifications
You must be signed in to change notification settings - Fork 0
/
signal_watcher.go
57 lines (48 loc) · 1.14 KB
/
signal_watcher.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package dominoes
import (
"context"
"os"
"os/signal"
)
type signalWatcher struct {
channel chan os.Signal
ctx context.Context
shutdown context.CancelFunc
inner ListenCloser
signals []os.Signal
logger logger
}
func newSignalWatcher(inner ListenCloser, config configuration) ListenCloser {
if len(config.signals) == 0 {
return inner
}
ctx, shutdown := context.WithCancel(context.Background())
return &signalWatcher{
channel: make(chan os.Signal, 4),
ctx: ctx,
shutdown: shutdown,
inner: inner,
logger: config.logger,
signals: config.signals,
}
}
func (this *signalWatcher) Listen() {
defer this.shutdown() // unblock wait method so we don't wait for signals anymore (in case Close() didn't get called)
go this.wait()
this.inner.Listen()
}
func (this *signalWatcher) wait() {
signal.Notify(this.channel, this.signals...)
select {
case value := <-this.channel:
this.logger.Printf("[INFO] Received signal [%s]. Closing...", value)
case <-this.ctx.Done():
}
signal.Stop(this.channel)
close(this.channel)
_ = this.inner.Close()
}
func (this *signalWatcher) Close() error {
this.shutdown()
return nil
}