-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmap_rule.go
57 lines (46 loc) · 967 Bytes
/
map_rule.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
package overloading
import (
"errors"
"reflect"
)
type MapRule struct {
m map[string]*Argument
}
func NewMapRule(args ...interface{}) *MapRule {
_len := len(args)
if _len%2 != 0 {
panic("Wrong argument length")
}
r := new(MapRule)
r.m = make(map[string]*Argument)
for i := 0; i < _len; i += 2 {
k := args[i].(string)
r.m[k] = args[i+1].(*Argument)
}
return r
}
func (r *MapRule) Check(args map[string]interface{}) (map[string]interface{}, error) {
out := make(map[string]interface{})
for k, v := range args {
arg, ok := r.m[k]
if !ok {
return out, errors.New("Unknown argument " + k)
}
t := reflect.TypeOf(v).String()
if t != arg.Type() {
return out, errors.New("Wrong argument type on " + k)
}
out[k] = v
}
for k := range r.m {
_, ok := args[k]
if !ok {
if r.m[k].IsOptional() {
out[k] = r.m[k].Default()
} else {
return out, errors.New("No default value on " + k)
}
}
}
return out, nil
}