/
matcher.go
126 lines (101 loc) · 2.47 KB
/
matcher.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
117
118
119
120
121
122
123
124
125
126
package filters
import (
"errors"
"fmt"
"regexp"
"strconv"
"time"
cache "github.com/patrickmn/go-cache"
)
var matchCache = cache.New(5*time.Minute, 1*time.Minute)
type matcherT interface {
setOperator(operator string)
GetOperator() string
Compare(valA, valB interface{}) bool
}
type abstractMatcher struct {
matcherT
Operator string
}
func (matcher *abstractMatcher) GetOperator() string {
return matcher.Operator
}
type equalMatcher struct {
abstractMatcher
}
func (matcher *equalMatcher) Compare(valA, valB interface{}) bool {
return valA == valB
}
type notEqualMatcher struct {
abstractMatcher
}
func (matcher *notEqualMatcher) Compare(valA, valB interface{}) bool {
return valA != valB
}
type moreThanMatcher struct {
abstractMatcher
}
func (matcher *moreThanMatcher) Compare(valA, valB interface{}) bool {
if valA == nil || valA == "" || valB == nil || valB == "" {
return false
}
if intA, ok := valA.(int); ok {
if intB, ok := valB.(int); ok {
return intA > intB
}
}
if atoiA, err := strconv.Atoi(valA.(string)); err == nil {
if atoiB, err := strconv.Atoi(valB.(string)); err == nil {
return atoiA > atoiB
}
}
return string(valA.(string)) > string(valB.(string))
}
type lessThanMatcher struct {
abstractMatcher
}
func (matcher *lessThanMatcher) Compare(valA, valB interface{}) bool {
if valA == nil || valA == "" || valB == nil || valB == "" {
return false
}
if intA, ok := valA.(int); ok {
if intB, ok := valB.(int); ok {
return intA < intB
}
}
if atoiA, err := strconv.Atoi(valA.(string)); err == nil {
if atoiB, err := strconv.Atoi(valB.(string)); err == nil {
return atoiA < atoiB
}
}
return string(valA.(string)) < string(valB.(string))
}
type regexpMatcher struct {
abstractMatcher
}
func (matcher *regexpMatcher) Compare(valA, valB interface{}) bool {
r, found := matchCache.Get(valB.(string))
if !found {
var err error
r, err = regexp.Compile("(?i)" + valB.(string))
if err != nil {
return false
}
matchCache.Set(valB.(string), r, 1*time.Minute)
}
return r.(*regexp.Regexp).MatchString(valA.(string))
}
type negativeRegexMatcher struct {
abstractMatcher
}
func (matcher *negativeRegexMatcher) Compare(valA, valB interface{}) bool {
r := regexpMatcher{}
return !r.Compare(valA, valB)
}
func newMatcher(matchType string) (matcherT, error) {
if m, found := matcherConfig[matchType]; found {
return m, nil
}
e := fmt.Sprintf("%s not matched with any know match type", matchType)
return nil, errors.New(e)
}