-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathany.go
65 lines (57 loc) · 1.01 KB
/
any.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
package secret
import (
"encoding/json"
"fmt"
)
// Any stores data in an encrypted state in memory, so that
// you don't accidentally leak these secrets via logging or whatever.
type Any[T any] struct {
encryptedMessage
plainText T
}
func New[T any](in T) Any[T] {
var s Any[T]
s.Set(in)
return s
}
func (s Any[T]) Get() T {
if len(s.encryptedMessage.data) == 0 {
var zeroValue T
return zeroValue
}
b := decrypt(s.encryptedMessage)
var t T
err := json.Unmarshal(b, &t)
if err != nil {
panic(err)
}
return t
}
func (s *Any[T]) GetPointer() *T {
if s == nil {
return nil
}
return ptr(s.Get())
}
func (s *Any[T]) Set(v T) {
b, err := json.Marshal(v)
if err != nil {
panic(err)
}
s.encryptedMessage = encrypt(b)
if !secrecyEnabled {
s.plainText = v
}
}
func (s *Any[T]) String() string {
if secrecyEnabled {
return "<HIDDEN>"
}
return fmt.Sprintf("%#v", s.plainText)
}
func (s Any[T]) GoString() string {
if secrecyEnabled {
return "<HIDDEN>"
}
return fmt.Sprintf("%#+v", s.plainText)
}