-
Notifications
You must be signed in to change notification settings - Fork 1
/
context.go
116 lines (104 loc) · 2.22 KB
/
context.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
package fastac
import (
"fmt"
"github.com/abichinger/fastac/model"
"github.com/abichinger/fastac/model/defs"
e "github.com/abichinger/fastac/model/effector"
m "github.com/abichinger/fastac/model/matcher"
"github.com/abichinger/fastac/str"
)
type ContextOption func(ctx *Context) error
func SetMatcher(matcher interface{}) ContextOption {
return func(ctx *Context) error {
var err error
switch mType := matcher.(type) {
case string:
if mType == "" {
break
}
m, ok := ctx.model.GetMatcher(mType)
if !ok {
mDef := defs.NewMatcherDef("", mType)
m, err = ctx.model.BuildMatcherFromDef(mDef)
if err != nil {
return err
}
}
ctx.matcher = m
case *defs.MatcherDef:
m, err := ctx.model.BuildMatcherFromDef(mType)
if err != nil {
return err
}
ctx.matcher = m
case m.IMatcher:
ctx.matcher = mType
}
return nil
}
}
func SetRequestDef(definition interface{}) ContextOption {
return func(ctx *Context) error {
switch rType := definition.(type) {
case string:
if rType == "" {
break
}
rDef, ok := ctx.model.GetRequestDef(rType)
if !ok {
return fmt.Errorf(str.ERR_REQUESTDEF_NOT_FOUND, rType)
}
ctx.rDef = rDef
case *defs.RequestDef:
ctx.rDef = rType
}
return nil
}
}
func SetEffector(effector interface{}) ContextOption {
return func(ctx *Context) error {
switch eType := effector.(type) {
case string:
if eType == "" {
break
}
eff, ok := ctx.model.GetEffector(eType)
if !ok {
eDef := defs.NewEffectDef("", eType)
eff = e.NewEffector(eDef)
}
ctx.effector = eff
case *defs.EffectDef:
eff := e.NewEffector(eType)
ctx.effector = eff
case e.IEffector:
ctx.effector = eType
}
return nil
}
}
type Context struct {
model model.IModel
rDef *defs.RequestDef
matcher m.IMatcher
effector e.IEffector
}
func NewContext(model model.IModel, options ...ContextOption) (*Context, error) {
ctx := &Context{}
ctx.model = model
for _, option := range options {
if err := option(ctx); err != nil {
return nil, err
}
}
if ctx.rDef == nil {
_ = SetRequestDef("r")(ctx)
}
if ctx.matcher == nil {
_ = SetMatcher("m")(ctx)
}
if ctx.effector == nil {
_ = SetEffector("e")(ctx)
}
return ctx, nil
}