-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexit.go
69 lines (59 loc) · 1.35 KB
/
exit.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
package exit
import (
"os"
"io"
"fmt"
)
// Represents the exit status of a program
type Status interface {
ExitCode() int
}
type exitCode int
func (e exitCode) ExitCode() int {
return int(e)
}
type msg struct {
code int
msg string
out io.Writer
}
func (m msg) ExitCode() int {
if m.out != nil {
fmt.Fprintln(m.out, m.msg)
} else {
fmt.Fprintln(os.Stderr, m.msg)
}
return m.code
}
// This should be the first deferred function in
// your code; it will respect all your deffered
// calls after it
func Handler() {
if e := recover(); e != nil {
if s, ok := e.(Status); ok {
os.Exit(s.ExitCode())
}
// not something that we can handle...
// time to panic lol
panic(e)
}
}
// Stops the program execution with the exit code 's.ExitCode()',
// honoring all deferred calls
func WithStatus(s Status) {
panic(s)
}
// Stops the program execution with the exit code 'code',
// honoring all deferred calls
func WithCode(code int) {
panic(exitCode(code))
}
// Stops the program execution with the exit code 'code',
// printing a message to 'w', and honoring all deferred calls
func WithMsg(w io.Writer, code int, format string, a ...interface{}) {
panic(msg{
out: w,
code: code,
msg: fmt.Sprintf(format, a...),
})
}