-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbehavior.go
34 lines (26 loc) · 949 Bytes
/
behavior.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
package mediator
import "context"
type BehaviorHandler func(ctx context.Context, command Command, next CommandHandler) (interface{}, error)
type Behavior interface {
WithBehavior(handler BehaviorHandler)
use(ctx context.Context, command Command, handler CommandHandler, index int) (interface{}, error)
}
type behavior struct {
behaviorHandlers []BehaviorHandler
}
func newBehavior() *behavior {
return &behavior{
behaviorHandlers: []BehaviorHandler{},
}
}
func (b *behavior) WithBehavior(handler BehaviorHandler) {
b.behaviorHandlers = append(b.behaviorHandlers, handler)
}
func (b *behavior) use(ctx context.Context, command Command, handler CommandHandler, index int) (interface{}, error) {
if index >= len(b.behaviorHandlers) {
return handler(ctx, command)
}
return b.behaviorHandlers[index](ctx, command, func(ctx context.Context, command Command) (interface{}, error) {
return b.use(ctx, command, handler, index+1)
})
}