-
Notifications
You must be signed in to change notification settings - Fork 0
/
guards.go
63 lines (53 loc) · 1.21 KB
/
guards.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
package decs
type Guard interface {
Inspect(command Command) error
}
func (cbus *CommandBus) AddGlobalGuard(guard Guard) {
cbus.AddCommandGuard("", guard)
}
func (cbus *CommandBus) AddCommandGuard(commandName string, guard Guard) {
if len(commandName) == 0 {
if !containsGuard(cbus.globalGuards, guard) {
cbus.globalGuards = append(cbus.globalGuards, guard)
}
return
}
gg := cbus.guards[commandName]
if gg == nil {
cbus.guards[commandName] = []Guard{guard}
return
}
if !containsGuard(gg, guard) {
gg = append(gg, guard)
}
}
func (cbus *CommandBus) RemoveGlobalGuard(guard Guard) {
cbus.RemoveCommandGuard("", guard)
}
func (cbus *CommandBus) RemoveCommandGuard(commandName string, guard Guard) {
if len(commandName) == 0 {
removeGuard(cbus.globalGuards, guard)
return
}
gg := cbus.guards[commandName]
if gg != nil {
removeGuard(gg, guard)
}
}
func index(guards []Guard, guard Guard) int {
for i, g := range guards {
if g == guard {
return i
}
}
return -1
}
func containsGuard(guards []Guard, guard Guard) bool {
return index(guards, guard) > -1
}
func removeGuard(guards []Guard, guard Guard) {
i := index(guards, guard)
if i > -1 {
guards = append(guards[:i], guards[i+1:]...)
}
}