forked from grafana/carbon-relay-ng
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmatcher.go
53 lines (48 loc) · 1.07 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
package main
import (
"bytes"
"regexp"
)
type Matcher struct {
Prefix string `json:"prefix,omitempty"`
Sub string `json:"substring,omitempty"`
Regex string `json:"regex,omitempty"`
// internal represenation for performance optimalization
prefix, substring []byte
regex *regexp.Regexp // compiled version of Regex
}
func NewMatcher(prefix, sub, regex string) (*Matcher, error) {
match := new(Matcher)
match.Prefix = prefix
match.Sub = sub
match.Regex = regex
err := match.updateInternals()
if err != nil {
return nil, err
}
return match, nil
}
func (m *Matcher) updateInternals() error {
m.prefix = []byte(m.Prefix)
m.substring = []byte(m.Sub)
if len(m.Regex) > 0 {
regexObj, err := regexp.Compile(m.Regex)
if err != nil {
return err
}
m.regex = regexObj
}
return nil
}
func (m *Matcher) Match(s []byte) bool {
if len(m.prefix) > 0 && !bytes.HasPrefix(s, m.prefix) {
return false
}
if len(m.substring) > 0 && !bytes.Contains(s, m.substring) {
return false
}
if m.regex != nil && !m.regex.Match(s) {
return false
}
return true
}