-
Notifications
You must be signed in to change notification settings - Fork 233
/
value_render.go
71 lines (61 loc) · 1.77 KB
/
value_render.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
package value_render
import (
"fmt"
"regexp"
"github.com/oliveagle/jsonpath"
)
var matchp, matchGoTemp, matchESIndex, jsonPath *regexp.Regexp
func init() {
matchp, _ = regexp.Compile(`^(\[.*?\])+$`)
matchGoTemp, _ = regexp.Compile(`{{.*}}`)
matchESIndex, _ = regexp.Compile(`%{.*?}`) //%{+YYYY.MM.dd}
jsonPath, _ = regexp.Compile(`^\$\.`)
}
type ValueRender interface {
Render(map[string]interface{}) interface{}
}
// getValueRender matches all regexp pattern and return a ValueRender
// return nil if no pattern matched
func getValueRender(template string) ValueRender {
if matchp.Match([]byte(template)) {
findp, _ := regexp.Compile(`(\[(.*?)\])`)
fields := make([]string, 0)
for _, v := range findp.FindAllStringSubmatch(template, -1) {
fields = append(fields, v[2])
}
if len(fields) == 1 {
return NewOneLevelValueRender(fields[0])
}
return NewMultiLevelValueRender(fields)
}
if matchGoTemp.Match([]byte(template)) {
return NewTemplateValueRender(template)
}
if matchESIndex.Match([]byte(template)) {
return NewIndexRender(template)
}
if jsonPath.Match([]byte(template)) {
pat, err := jsonpath.Compile(template)
if err != nil {
panic(fmt.Sprintf("json path compile `%s` error: %s", template, err))
}
return &JsonpathRender{pat}
}
return nil
}
// GetValueRender return a ValueRender, and return LiteralValueRender if no pattern matched
func GetValueRender(template string) ValueRender {
r := getValueRender(template)
if r != nil {
return r
}
return NewLiteralValueRender(template)
}
// GetValueRender2 return a ValueRender, and return OneLevelValueRender("message") if no pattern matched
func GetValueRender2(template string) ValueRender {
r := getValueRender(template)
if r != nil {
return r
}
return NewOneLevelValueRender(template)
}