-
Notifications
You must be signed in to change notification settings - Fork 6
/
id.go
77 lines (60 loc) · 1.28 KB
/
id.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
package hide
import (
"database/sql/driver"
"encoding/json"
"errors"
"strings"
)
// ID type that can be used as an replacement for int64.
// It is converted to/from a hash value when marshalled to/from JSON.
// Value 0 is considered null.
type ID int64
// Scan implements the Scanner interface.
func (hide *ID) Scan(value interface{}) error {
if value == nil {
*hide = 0
return nil
}
id, ok := value.(int64)
if !ok {
return errors.New("unexpected type")
}
*hide = ID(id)
return nil
}
// Value implements the driver Valuer interface.
func (hide ID) Value() (driver.Value, error) {
if hide == 0 {
return nil, nil
}
return int64(hide), nil
}
// MarshalJSON implements the encoding json interface.
func (hide ID) MarshalJSON() ([]byte, error) {
if hide == 0 {
return json.Marshal(nil)
}
result, err := hash.Encode(hide)
if err != nil {
return nil, err
}
return json.Marshal(string(result))
}
// UnmarshalJSON implements the encoding json interface.
func (hide *ID) UnmarshalJSON(data []byte) error {
// convert null to 0
if strings.TrimSpace(string(data)) == "null" {
*hide = 0
return nil
}
// remove quotes
if len(data) >= 2 {
data = data[1 : len(data)-1]
}
result, err := hash.Decode(data)
if err != nil {
return err
}
*hide = result
return nil
}