/
string_encrypted.go
82 lines (68 loc) · 1.45 KB
/
string_encrypted.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
77
78
79
80
81
82
package jsontostruct
import (
"database/sql/driver"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"strings"
)
type StringEncrypted string
// func (c StringEncrypted) MarshalJSON() ([]byte, error) {
// return []byte(*c.String()), nil
// }
func (c *StringEncrypted) UnmarshalJSON(data []byte) error {
var value string
if err := json.Unmarshal(data, &value); err != nil {
return err
}
if strings.HasPrefix(value, "0x02") {
decoded, err := hex.DecodeString(strings.TrimPrefix(value, "0x"))
if err != nil {
return err
}
value, err = DecryptByPassphrase(decoded)
if err != nil {
return err
}
}
var newVal string
for _, v := range value {
if v == 160 { // for &nsbp
newVal += " "
continue
}
newVal += string(v)
}
newVal = strings.ReplaceAll(newVal, "'", `"`)
*c = StringEncrypted(newVal)
return nil
}
func (c *StringEncrypted) IsNil() bool {
return c == nil
}
func (c *StringEncrypted) String() *string {
if c.IsNil() {
return nil
}
val := string(*c)
return &val
}
func (c *StringEncrypted) Scan(value interface{}) error {
switch t := value.(type) {
case string:
*c = StringEncrypted(t)
case []byte:
*c = StringEncrypted(string(t))
case *string:
*c = StringEncrypted(*t)
case *[]byte:
*c = StringEncrypted(string(*t))
default:
return errors.New(fmt.Sprint("failed to unmarshal String value:", value))
}
return nil
}
func (c StringEncrypted) Value() (driver.Value, error) {
return c.String(), nil
}