-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsignal.go
71 lines (57 loc) · 1.37 KB
/
signal.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package morecontext
import (
"context"
"fmt"
"os"
"os/signal"
"sync"
"syscall"
)
// sigCtx is a context that will be cancelled if certain signals are received.
// Its Err will include details if this is the reason it was cancelled.
type sigCtx struct {
context.Context
exitSignal os.Signal
m sync.Mutex
}
// Err implements context.Context.Err but includes the os.Signal that caused
// the context cancellation.
func (sc *sigCtx) Err() error {
sc.m.Lock()
defer sc.m.Unlock()
err := sc.Context.Err()
if sc.exitSignal == nil {
return nil
}
return &MessageError{
Message: fmt.Sprintf("context cancelled: got signal %s", sc.exitSignal.String()),
Original: err,
}
}
// ForSignals returns a context.Context that will be cancelled if the given
// signals (or SIGTERM and SIGINT by default, if none are passed) are received
// by the process.
func ForSignals(sigs ...os.Signal) context.Context {
ctx, cancel := context.WithCancel(context.Background())
// If no signals are returnd we will use a sensible default set.
if len(sigs) == 0 {
sigs = []os.Signal{syscall.SIGTERM, syscall.SIGINT}
}
sc := &sigCtx{Context: ctx}
ch := make(chan os.Signal, 2)
signal.Notify(ch, sigs...)
go func() {
i := 0
for sig := range ch {
i++
if i > 1 {
os.Exit(1)
}
sc.m.Lock()
sc.exitSignal = sig
sc.m.Unlock()
cancel()
}
}()
return sc
}