forked from jrallison/go-workers
-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.go
48 lines (39 loc) · 978 Bytes
/
middleware.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
package workers
type Action interface {
Call(queue string, message *Msg, next func() bool) bool
}
type Middlewares struct {
actions []Action
}
func (m *Middlewares) Append(action Action) {
m.actions = append(m.actions, action)
}
func (m *Middlewares) Prepend(action Action) {
actions := make([]Action, len(m.actions)+1)
actions[0] = action
copy(actions[1:], m.actions)
m.actions = actions
}
func (m *Middlewares) call(queue string, message *Msg, final func()) bool {
return continuation(m.actions, queue, message, final)()
}
func continuation(actions []Action, queue string, message *Msg, final func()) func() bool {
return func() (acknowledge bool) {
if len(actions) > 0 {
acknowledge = actions[0].Call(
queue,
message,
continuation(actions[1:], queue, message, final),
)
if !acknowledge {
return
}
} else {
final()
}
return true
}
}
func NewMiddleware(actions ...Action) *Middlewares {
return &Middlewares{actions}
}