-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcallbacks.go
More file actions
80 lines (65 loc) · 1.53 KB
/
callbacks.go
File metadata and controls
80 lines (65 loc) · 1.53 KB
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
package exitplan
import (
"context"
"fmt"
"path/filepath"
"runtime"
"time"
)
type CallbackErr struct {
Name string
Err error
}
func (e *CallbackErr) Error() string {
return fmt.Sprintf("callback %s: %v", e.Name, e.Err)
}
func (e *CallbackErr) Unwrap() error {
return e.Err
}
type exitCallbackOpt func(*callback)
// Async sets the callback to be executed in a separate goroutine.
// Exitplan will wait for all Async callbacks to complete before exiting.
// Use Timeout to bound the callback.
func Async(c *callback) {
c.executeBehaviour = executeAsync
}
// PanicOnError sets the callback to panic with the error returned by the callback.
func PanicOnError(c *callback) {
c.errorBehaviour = panicOnError
}
// Timeout sets the timeout for the callback.
func Timeout(timeout time.Duration) exitCallbackOpt {
return func(c *callback) {
c.timeout = timeout
}
}
// Name sets callback name, used for identification.
func Name(name string) exitCallbackOpt {
return func(c *callback) {
c.name = name
}
}
type executeBehaviour int
const (
executeSync executeBehaviour = iota
executeAsync
)
type exitBehaviour int
const (
carryOnWithError exitBehaviour = iota
panicOnError
)
type callback struct {
name string
executeBehaviour executeBehaviour
errorBehaviour exitBehaviour
timeout time.Duration
fn func(context.Context) error
}
func callerLocation(skip int) string {
_, file, line, ok := runtime.Caller(skip)
if !ok {
return "unknown"
}
return fmt.Sprintf("%s:%d", filepath.Base(file), line)
}