-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathshutdown.go
More file actions
52 lines (44 loc) · 1.12 KB
/
shutdown.go
File metadata and controls
52 lines (44 loc) · 1.12 KB
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 shutdown
import (
"context"
"errors"
"os"
"os/signal"
"syscall"
)
var defaultSignals = []os.Signal{
syscall.SIGHUP,
syscall.SIGINT,
syscall.SIGTERM,
}
// Wait accepts a callback function and waits for the callback to return or for
// a signal to trigger. If nil is passed instead of a function, Wait will block
// until a signal triggers.
func Wait(blocking func() error, signals ...os.Signal) error {
return WaitContext(context.Background(), blocking, signals...)
}
// WaitContext behaves like Wait but with a parent context, which may include a
// deadline or a custom cancellation.
func WaitContext(parent context.Context, blocking func() error, signals ...os.Signal) error {
if len(signals) == 0 {
signals = defaultSignals
}
ctx, stop := signal.NotifyContext(parent, signals...)
defer stop()
if blocking == nil {
blocking = func() error { <-ctx.Done(); return nil }
}
errs := make(chan error, 1)
go func() {
errs <- blocking()
}()
select {
case err := <-errs:
return err
case <-ctx.Done():
if err := ctx.Err(); err != nil && !errors.Is(err, context.Canceled) {
return err
}
}
return nil
}