-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathengine.go
92 lines (79 loc) · 1.56 KB
/
engine.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
package ginplus
import (
"os"
"os/signal"
"syscall"
)
type (
// Starter 开始方法的接口
Starter interface {
Start() error
}
// Stopper 结束方法的接口
Stopper interface {
Stop()
}
Server interface {
// Starter 启动服务
Starter
// Stopper 停止服务
Stopper
}
// CtrlC 捕获ctrl-c的控制器
CtrlC struct {
servers []Server
// 信号通道
signalChan chan os.Signal
}
)
// NewCtrlC 初始化生成CtrlC
func NewCtrlC(services ...Server) *CtrlC {
return &CtrlC{
servers: services,
signalChan: make(chan os.Signal, 1),
}
}
// 等待键盘信号
func (c *CtrlC) waitSignals(signals ...os.Signal) {
signal.Notify(c.signalChan, signals...)
<-c.signalChan
}
// 接收到kill信号
func (c *CtrlC) waitKill() {
c.waitSignals(os.Interrupt, syscall.SIGTERM, syscall.SIGHUP)
}
func (c *CtrlC) recover() {
if err := recover(); err != nil {
Logger().Sugar().Panicf("panic: %v", err)
c.signalChan <- os.Kill
}
}
// Start 开始运行程序,遇到os.Interrupt停止
func (c *CtrlC) Start() {
go func() {
defer c.recover()
// 启动程序内部的服务列表
c.startMulServices()
}()
c.waitKill()
c.stopMulServices()
}
// 启动应用子服务
func (c *CtrlC) startMulServices() {
servicesSlice := c.servers
for _, service := range servicesSlice {
go func(s Starter) {
defer c.recover()
if err := s.Start(); err != nil {
panic(err)
}
}(service)
}
}
// 停止应用子服务
func (c *CtrlC) stopMulServices() {
servicesSlice := c.servers
for _, service := range servicesSlice {
service.Stop()
}
}