forked from naoina/kocha
-
Notifications
You must be signed in to change notification settings - Fork 0
/
unit.go
44 lines (39 loc) · 1010 Bytes
/
unit.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
package kocha
import (
"errors"
"reflect"
)
var (
ErrInvokeDefault = errors.New("invoke default")
)
var failedUnits = make(map[string]bool)
// Unit is an interface that Unit for FeatureToggle.
type Unit interface {
// ActiveIf returns whether the Unit is active.
ActiveIf() bool
}
// Invoke invokes newFunc.
// It invokes newFunc but will behave to fallback.
// When unit.ActiveIf returns false or any errors occurred in invoking, it invoke the defaultFunc if defaultFunc isn't nil.
// Also if any errors occurred at least once, next invoking will always invoke the defaultFunc.
func Invoke(unit Unit, newFunc func(), defaultFunc func()) {
name := reflect.TypeOf(unit).String()
defer func() {
if err := recover(); err != nil {
if err != ErrInvokeDefault {
logStackAndError(err)
failedUnits[name] = true
}
if defaultFunc != nil {
defaultFunc()
}
}
}()
if failedUnits[name] {
panic(ErrInvokeDefault)
}
if !unit.ActiveIf() {
panic(ErrInvokeDefault)
}
newFunc()
}