-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathint.go
More file actions
92 lines (68 loc) · 1.32 KB
/
int.go
File metadata and controls
92 lines (68 loc) · 1.32 KB
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
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
}
switch b := value.(type) {
case int:
ni.Int, ni.Valid = b, true
case int8:
ni.Int, ni.Valid = int(b), true
case int16:
ni.Int, ni.Valid = int(b), true
case int32:
ni.Int, ni.Valid = int(b), true
case int64:
ni.Int, ni.Valid = int(b), true
case []byte:
a, err := strconv.Atoi(string(b))
if err != nil {
return errors.New("type assertion to int is failed")
}
ni.Int, ni.Valid = a, true
default:
return errors.New("type assertion to int is failed")
}
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
}