filters.go
2.0 KB
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
package filter
import (
"strings"
"github.com/globalsign/mgo/bson"
"github.com/tal-tech/go-stash/stash/config"
)
const (
filterDrop = "drop"
filterRemoveFields = "remove_field"
opAnd = "and"
opOr = "or"
typeContains = "contains"
typeMatch = "match"
)
type FilterFunc func(map[string]interface{}) map[string]interface{}
func CreateFilters(c config.Config) []FilterFunc {
var filters []FilterFunc
for _, f := range c.Filters {
switch f.Action {
case filterDrop:
filters = append(filters, DropFilter(f.Conditions))
case filterRemoveFields:
filters = append(filters, RemoveFieldFilter(f.Fields))
}
}
return filters
}
func DropFilter(conds []config.Condition) FilterFunc {
return func(m map[string]interface{}) map[string]interface{} {
var qualify bool
for _, cond := range conds {
var qualifyOnce bool
switch cond.Type {
case typeMatch:
qualifyOnce = cond.Value == m[cond.Key]
case typeContains:
if val, ok := m[cond.Key].(string); ok {
qualifyOnce = strings.Contains(val, cond.Value)
}
}
switch cond.Op {
case opAnd:
if !qualifyOnce {
return m
} else {
qualify = true
}
case opOr:
if qualifyOnce {
qualify = true
}
}
}
if qualify {
return nil
} else {
return m
}
}
}
func RemoveFieldFilter(fields []string) FilterFunc {
return func(m map[string]interface{}) map[string]interface{} {
for _, field := range fields {
delete(m, field)
}
return m
}
}
func AddUriFieldFilter(inField, outFirld string) FilterFunc {
return func(m map[string]interface{}) map[string]interface{} {
if val, ok := m[inField].(string); ok {
var datas []string
idx := strings.Index(val, "?")
if idx < 0 {
datas = strings.Split(val, "/")
} else {
datas = strings.Split(val[:idx], "/")
}
for i, data := range datas {
if bson.IsObjectIdHex(data) {
datas[i] = "*"
}
}
m[outFirld] = strings.Join(datas, "/")
}
return m
}
}