-
Notifications
You must be signed in to change notification settings - Fork 1
/
censor.go
74 lines (63 loc) · 1.65 KB
/
censor.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
package masq
import (
"reflect"
"regexp"
"strings"
)
// Censor is a function to check if the field should be redacted. It receives field name, value, and tag of struct if the value is in struct.
// If the field should be redacted, it returns true.
type Censor func(fieldName string, value any, tag string) bool
type Censors []Censor
func (x Censors) ShouldRedact(fieldName string, value any, tag string) bool {
for _, censor := range x {
if censor(fieldName, value, tag) {
return true
}
}
return false
}
// string
func newStringCensor(target string) Censor {
return func(fieldName string, value any, tag string) bool {
v := reflect.ValueOf(value)
if v.Kind() != reflect.String {
return false
}
return strings.Contains(v.String(), target)
}
}
// regex
func newRegexCensor(target *regexp.Regexp) Censor {
return func(fieldName string, value any, tag string) bool {
v := reflect.ValueOf(value)
if v.Kind() != reflect.String {
return false
}
return target.FindString(v.String()) != ""
}
}
// type
func newTypeCensor[T any]() Censor {
return func(fieldName string, value any, tag string) bool {
var v T
return reflect.TypeOf(v) == reflect.TypeOf(value)
}
}
// tag
func newTagCensor(tagValue string) Censor {
return func(fieldName string, value any, tag string) bool {
return tag == tagValue
}
}
// field name
func newFieldNameCensor(name string) Censor {
return func(fieldName string, value any, tag string) bool {
return name == fieldName
}
}
// field name prefix
func newFieldPrefixCensor(prefix string) Censor {
return func(fieldName string, value any, tag string) bool {
return strings.HasPrefix(fieldName, prefix)
}
}