-
Notifications
You must be signed in to change notification settings - Fork 4
/
rules.go
80 lines (74 loc) · 1.47 KB
/
rules.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
package gorules
import (
"errors"
"go/ast"
"go/parser"
"reflect"
)
// Rule ...
type Rule interface {
Bool(interface{}) (bool, error)
Int(interface{}) (int64, error)
Float(interface{}) (float64, error)
}
type rule struct {
expr ast.Expr
}
// NewRule 提前解析规则,不用每次都重新解析
func NewRule(r string) (Rule, error) {
if len(r) == 0 {
return nil, ErrRuleEmpty
}
expr, err := parser.ParseExpr(r)
if err != nil {
return nil, err
}
return &rule{expr}, nil
}
func (r *rule) Bool(x interface{}) (bool, error) {
typ := reflect.ValueOf(x)
if typ.Kind() == reflect.Ptr {
typ = typ.Elem()
}
b, err := getValue(typ, r.expr)
if err != nil {
return false, err
}
if r, ok := b.(bool); ok {
return r, nil
}
return false, errors.New("result not bool")
}
func (r *rule) Int(x interface{}) (int64, error) {
typ := reflect.ValueOf(x)
if typ.Kind() == reflect.Ptr {
typ = typ.Elem()
}
b, err := getValue(typ, r.expr)
if err != nil {
return 0, err
}
if r, ok := b.(float64); ok {
return int64(r), nil
} else if i, ok := b.(int64); ok {
return i, nil
}
return 0, errors.New("result not int")
}
func (r *rule) Float(x interface{}) (float64, error) {
typ := reflect.ValueOf(x)
if typ.Kind() == reflect.Ptr {
typ = typ.Elem()
}
b, err := getValue(typ, r.expr)
if err != nil {
return 0, err
}
if r, ok := b.(float64); ok {
return r, nil
}
if r, ok := b.(int64); ok {
return float64(r), nil
}
return 0, errors.New("result not float")
}