-
Notifications
You must be signed in to change notification settings - Fork 0
/
atexit.go
76 lines (61 loc) · 1.55 KB
/
atexit.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
/* Simple atexit implementation. Add handlers using Register, you must call
atexit.Exit to get the handler invoked (and then terminate the program).
This package also provides replacements to log.Fatal, log.Fatalf and log.Fatalln.
Example:
package main
import (
"atexit"
"fmt"
)
func handler() {
fmt.Println("Exiting")
}
func main() {
atexit.Register(handler)
atexit.Exit(0)
}
*/
package atexit
import (
"fmt"
"log"
"os"
)
var handlers = []func(){}
func runHandler(handler func()) {
defer func() {
if err := recover(); err != nil {
fmt.Fprintln(os.Stderr, "error: atexit handler error:", err)
}
}()
handler()
}
func runHandlers() {
for _, handler := range handlers {
runHandler(handler)
}
}
// Exit runs all the atexit handlers and then terminates the program using os.Exit(code)
func Exit(code int) {
runHandlers()
os.Exit(code)
}
// Fatal runs all the atexit handler then calls log.Fatal (which will terminate the program)
func Fatal(v ...interface{}) {
runHandlers()
log.Fatal(v...)
}
// Fatalf runs all the atexit handler then calls log.Fatalf (which will terminate the program)
func Fatalf(format string, v ...interface{}) {
runHandlers()
log.Fatalf(format, v...)
}
// Fatalln runs all the atexit handler then calls log.Fatalln (which will terminate the program)
func Fatalln(v ...interface{}) {
runHandlers()
log.Fatalln(v...)
}
// Add atexit handler, call atexit.Exit to invoke all handlers.
func Register(handler func()) {
handlers = append(handlers, handler)
}