-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsig.go
52 lines (41 loc) · 845 Bytes
/
sig.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
package sig
import (
"os"
"os/signal"
"syscall"
"context"
)
type SigReceivedHandler interface {
Handle(os.Signal)
}
type SigReceivedHandlerFunc func(os.Signal)
func (s SigReceivedHandlerFunc) Handle(sig os.Signal) {
s(sig)
}
type Handler struct {
onSignalReceived SigReceivedHandler
sigCh chan os.Signal
}
func New(h SigReceivedHandler, sigs ...os.Signal) *Handler {
if len(sigs) == 0 {
sigs = append(sigs, syscall.SIGTERM, syscall.SIGINT, syscall.SIGHUP)
}
ch := make(chan os.Signal, 1)
signal.Notify(ch, sigs...)
return &Handler{
onSignalReceived: h,
sigCh: ch,
}
}
func (h *Handler) Loop(ctx context.Context, cancel func()) error {
defer cancel()
for {
select {
case <-ctx.Done():
return ctx.Err()
case sig := <-h.sigCh:
h.onSignalReceived.Handle(sig)
return nil
}
}
}