-
Notifications
You must be signed in to change notification settings - Fork 0
/
replace.go
75 lines (61 loc) · 1.57 KB
/
replace.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
package main
import (
"fmt"
"strings"
"regexp"
"reflect"
"github.com/pkg/errors"
"github.com/elastic/beats/libbeat/beat"
"github.com/elastic/beats/libbeat/common"
"github.com/elastic/beats/libbeat/processors"
)
type Replace struct {
config ReplaceConfig
}
func (r Replace) String() string {
return fmt.Sprintf("config => %#v", r.config)
}
func New(c *common.Config) (processors.Processor, error) {
rc := defaultReplaceConfig
err := c.Unpack(&rc)
if err != nil {
return nil, errors.Wrap(err, "failed to unpack replace config")
}
return &Replace{
config: rc,
}, nil
}
func (r *Replace) Run(event *beat.Event) (*beat.Event, error) {
var findInField = r.config.Field
if findInField == "" {
findInField = defaultReplaceConfig.Field
}
fieldObject, _ := event.GetValue(findInField)
val := reflect.ValueOf(fieldObject)
// Follow the pointer.
if val.Kind() == reflect.Ptr && !val.IsNil() {
val = reflect.ValueOf(val.Elem().Interface())
}
var fieldText = ""
if val.IsValid() {
fieldText = fmt.Sprintf("%v", val.Interface())
} else {
return event, nil
}
var target = r.config.Target
if target == "" {
target = findInField
}
if fieldText == "" || r.config.Find == "" {
event.PutValue(target, fieldText)
} else if r.config.Regex {
replacer := regexp.MustCompile(r.config.Find)
result := replacer.ReplaceAllString(fieldText, r.config.Replace)
event.PutValue(target, result)
} else {
replacer := strings.NewReplacer(r.config.Find, r.config.Replace)
result := replacer.Replace(fieldText)
event.PutValue(target, result)
}
return event, nil
}