-
Notifications
You must be signed in to change notification settings - Fork 16
/
middlewares.go
89 lines (82 loc) · 1.9 KB
/
middlewares.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
77
78
79
80
81
82
83
84
85
86
87
88
89
package machine
import (
"fmt"
"time"
)
// Cron is a middleware that execute the function every time the ticker ticks until the goroutine's context cancels
func Cron(ticker *time.Ticker) Middleware {
return func(fn Func) Func {
return func(routine Routine) {
defer ticker.Stop()
for {
select {
case <-routine.Context().Done():
return
case <-ticker.C:
fn(routine)
}
}
}
}
}
// While is a middleware that will execute the Func while deciderFunc() returns true or the context cancels.
func While(deciderFunc func(routine Routine) bool) Middleware {
return func(fn Func) Func {
return func(routine Routine) {
for {
select {
case <-routine.Context().Done():
return
default:
if !deciderFunc(routine) {
continue
}
fn(routine)
}
}
}
}
}
// After exectues the afterFunc after the main goroutine exits.
func After(afterFunc func(routine Routine)) Middleware {
return func(fn Func) Func {
return func(routine Routine) {
fn(routine)
afterFunc(routine)
}
}
}
// Before exectues the beforeFunc before the main goroutine is executed.
func Before(beforeFunc func(routine Routine)) Middleware {
return func(fn Func) Func {
return func(routine Routine) {
beforeFunc(routine)
fn(routine)
}
}
}
// Decider exectues the deciderFunc before the main goroutine is executed.
// If it returns false, the goroutine won't be executed.
func Decider(deciderFunc func(routine Routine) bool) Middleware {
return func(fn Func) Func {
return func(routine Routine) {
if deciderFunc(routine) {
fn(routine)
}
}
}
}
// PanicRecover wraps a goroutine with a middleware the recovers from panics.
func PanicRecover() Middleware {
return func(fn Func) Func {
return func(routine Routine) {
defer func() {
r := recover()
if _, ok := r.(error); ok {
fmt.Println("machine: panic recovered")
}
}()
fn(routine)
}
}
}