-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathexit.go
More file actions
55 lines (47 loc) · 948 Bytes
/
exit.go
File metadata and controls
55 lines (47 loc) · 948 Bytes
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
package command
import (
"os"
"reflect"
"sync"
)
type exit struct {
lock sync.RWMutex
funcs []interface{}
}
var Exit = &exit{funcs: make([]interface{}, 0, 5)}
//注只支持func()或者func()error类型的函数
//用来做清理用的
func (self *exit) RegisterFunc(f interface{}) {
self.lock.Lock()
defer self.lock.Unlock()
typ := reflect.TypeOf(f).String()
if typ != "func()" && typ != "func() error" {
return
}
self.funcs = append(self.funcs, f)
}
//执行所有的函数,并清空self.funcs
func (self *exit) Exec() {
self.lock.RLock()
defer self.lock.RUnlock()
for _, f := range self.funcs {
switch reflect.TypeOf(f).String() {
case "func()":
fn, ok := f.(func())
if ok {
fn()
}
case "func() error":
fn, ok := f.(func() error)
if ok {
fn()
}
}
}
self.funcs = self.funcs[:0]
}
//执行所有的函数,并退出程序
func (self *exit) Exit(code int) {
self.Exec()
os.Exit(code)
}