-
Notifications
You must be signed in to change notification settings - Fork 14
/
string_match.go
79 lines (61 loc) · 1.58 KB
/
string_match.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
package condition
import (
"context"
"encoding/json"
"fmt"
"regexp"
"github.com/brexhq/substation/config"
iconfig "github.com/brexhq/substation/internal/config"
"github.com/brexhq/substation/internal/errors"
"github.com/brexhq/substation/message"
)
type stringMatchConfig struct {
Object iconfig.Object `json:"object"`
// Pattern is the regular expression used during inspection.
Pattern string `json:"pattern"`
}
func (c *stringMatchConfig) Decode(in interface{}) error {
return iconfig.Decode(in, c)
}
func (c *stringMatchConfig) Validate() error {
if c.Pattern == "" {
return fmt.Errorf("pattern: %v", errors.ErrMissingRequiredOption)
}
return nil
}
func newStringMatch(_ context.Context, cfg config.Config) (*stringMatch, error) {
conf := stringMatchConfig{}
if err := conf.Decode(cfg.Settings); err != nil {
return nil, err
}
if err := conf.Validate(); err != nil {
return nil, err
}
re, err := regexp.Compile(conf.Pattern)
if err != nil {
return nil, fmt.Errorf("condition: insp_regexp: %v", err)
}
insp := stringMatch{
conf: conf,
re: re,
}
return &insp, nil
}
type stringMatch struct {
conf stringMatchConfig
re *regexp.Regexp
}
func (insp *stringMatch) Inspect(ctx context.Context, msg *message.Message) (output bool, err error) {
if msg.IsControl() {
return false, nil
}
if insp.conf.Object.SourceKey == "" {
return insp.re.Match(msg.Data()), nil
}
value := msg.GetValue(insp.conf.Object.SourceKey)
return insp.re.MatchString(value.String()), nil
}
func (c *stringMatch) String() string {
b, _ := json.Marshal(c.conf)
return string(b)
}