-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathboot.go
97 lines (83 loc) · 1.94 KB
/
boot.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package goarc
import (
"context"
"os"
"os/signal"
"syscall"
)
// Up manages the lifecycle of a service. It blocks until the service shuts down or the service.Start() method returns.
// It listens to specific signals and gracefully shut down the service when any of these signals are received:
//
// syscall.SIGINT
// syscall.SIGTERM
// syscall.SIGQUIT
// syscall.SIGABRT
//
// It exits with a non-zero status code if an error occurs during either the startup or shutdown process.
func Up(s Service, opt ...BootOpt) {
opts := defaultBootOpts
opts.apply(opt...)
var ch chan error
go func(s Service) {
sig := make(chan os.Signal, 1)
// e.g. kill -SIGQUIT <pid>
// Notify the channel for the specified signals
signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT, syscall.SIGABRT)
// Block until a signal is received
select {
case <-opts.ctx.Done():
case <-sig:
}
ch = make(chan error)
// Attempt to stop the service
ch <- s.Stop()
}(s)
// Start the service
err := s.Start()
opts.onStart(err)
if ch != nil {
opts.onStop(<-ch)
}
}
type BootOpt func(*bootOpts)
type bootOpts struct {
ctx context.Context
onStart func(error)
onStop func(error)
}
func (b *bootOpts) apply(opt ...BootOpt) {
for _, o := range opt {
o(b)
}
}
var defaultBootOpts = bootOpts{
// An empty Context. It is never canceled, has no values, and has no deadline.
ctx: context.Background(),
// If an error occurs during startup, exit with a non-zero status code
onStart: func(err error) {
if err != nil {
os.Exit(1)
}
},
// If an error occurs during service stop, exit with a non-zero status code
onStop: func(err error) {
if err != nil {
os.Exit(1)
}
},
}
func Context(ctx context.Context) BootOpt {
return func(b *bootOpts) {
b.ctx = ctx
}
}
func OnStart(f func(error)) BootOpt {
return func(b *bootOpts) {
b.onStart = f
}
}
func OnStop(f func(error)) BootOpt {
return func(b *bootOpts) {
b.onStop = f
}
}