-
Notifications
You must be signed in to change notification settings - Fork 14
/
sensitivestring.go
76 lines (63 loc) · 1.59 KB
/
sensitivestring.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
package common
import (
"encoding/json"
"reflect"
"github.com/anz-bank/sysl-go/validator"
)
const DefaultReplacementText = "****************"
type SensitiveString struct {
s string
replacement *string
}
func NewSensitiveString(from string) SensitiveString {
r := DefaultReplacementText
return SensitiveString{from, &r}
}
func (s SensitiveString) String() string {
if s.replacement == nil {
r := DefaultReplacementText
s.replacement = &r
}
return *s.replacement
}
func (s *SensitiveString) Value() string {
return s.s
}
func (s *SensitiveString) UnmarshalYAML(unmarshal func(interface{}) error) error {
var val string
if err := unmarshal(&val); err != nil {
return err
}
s.s = val
return nil
}
// Note, this one needs to be an object receiver NOT a pointer receiver.
func (s SensitiveString) MarshalYAML() (interface{}, error) {
return s.String(), nil
}
func (s *SensitiveString) UnmarshalJSON(data []byte) error {
var val string
if err := json.Unmarshal(data, &val); err != nil {
return err
}
s.s = val
return nil
}
func (s *SensitiveString) MarshalJSON() ([]byte, error) {
return json.Marshal(s.String())
}
func sensitiveStringValidator(field reflect.Value) interface{} {
switch field.Interface().(type) {
case SensitiveString:
val := field.Interface().(SensitiveString)
return val.Value()
case *SensitiveString:
val := field.Interface().(*SensitiveString)
return val.Value()
}
return nil
}
//nolint:gochecknoinits // We must use init here to setup a custom validator
func init() {
validator.RegisterCustomValidator(sensitiveStringValidator, SensitiveString{})
}