-
Notifications
You must be signed in to change notification settings - Fork 702
/
hooks.go
62 lines (49 loc) · 1.07 KB
/
hooks.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
package hooks
import (
"fmt"
"sync"
"github.com/douyu/jupiter/pkg/util/xcolor"
)
var (
globalHooks = make(map[Stage][]func())
mu = sync.RWMutex{}
)
type Stage int
func (s Stage) String() string {
switch s {
case Stage_BeforeLoadConfig:
return "BeforeLoadConfig"
case Stage_AfterLoadConfig:
return "AfterLoadStart"
case Stage_BeforeStop:
return "BeforeStop"
case Stage_AfterStop:
return "AfterStop"
}
return "Unkown"
}
const (
Stage_BeforeLoadConfig Stage = iota + 1
Stage_AfterLoadConfig
Stage_BeforeStop
Stage_AfterStop
)
// Register 注册一个defer函数
func Register(stage Stage, fns ...func()) {
mu.Lock()
defer mu.Unlock()
globalHooks[stage] = append(globalHooks[stage], fns...)
}
// Do 执行
func Do(stage Stage) {
mu.Lock()
defer mu.Unlock()
fmt.Printf("[jupiter] %+v\n", xcolor.Green(fmt.Sprintf("hook stage (%s)...", stage)))
for i := len(globalHooks[stage]) - 1; i >= 0; i-- {
fn := globalHooks[stage][i]
if fn != nil {
fn()
}
}
fmt.Printf("[jupiter] %+v\n", xcolor.Green(fmt.Sprintf("hook stage (%s)... done", stage)))
}