-
Notifications
You must be signed in to change notification settings - Fork 0
/
int.go
97 lines (66 loc) · 1.17 KB
/
int.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package nullish
import (
"bytes"
"database/sql/driver"
"errors"
"strconv"
"github.com/goccy/go-json"
)
type NullInt struct {
Int int
Valid bool
}
// Value method
func (ni NullInt) Value() (driver.Value, error) {
if !ni.Valid {
return nil, nil
}
return ni.Int, nil
}
// Scan method
func (ni *NullInt) Scan(value interface{}) error {
if value == nil {
ni.Int, ni.Valid = 0, false
return nil
}
var res int
switch b := value.(type) {
case int8:
res = int(b)
case int16:
res = int(b)
case int32:
res = int(b)
case int64:
res = int(b)
case []byte:
a, err := strconv.Atoi(string(b))
if err != nil {
return errors.New("type assertion to int is failed")
}
res = a
}
ni.Int, ni.Valid = res, true
return nil
}
// MarshalJSON method
func (ni NullInt) MarshalJSON() ([]byte, error) {
if !ni.Valid {
return NullType, nil
}
return json.Marshal(ni.Int)
}
// UnmarshalJSON method
func (ni *NullInt) UnmarshalJSON(data []byte) error {
if bytes.Equal(data, NullType) {
*ni = NullInt{}
return nil
}
var res int
err := json.Unmarshal(data, &res)
if err != nil {
return err
}
*ni = NullInt{Int: res, Valid: true}
return nil
}