-
Notifications
You must be signed in to change notification settings - Fork 2
/
int32.go
61 lines (54 loc) · 1.16 KB
/
int32.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
package nulltypes
import (
"database/sql/driver"
"encoding/json"
)
// NullInt32 is a wrapper around int32
type NullInt32 struct {
Int32 int32
Valid bool
}
// Int32 method to get NullInt32 object from int32
func Int32(Int32 int32) NullInt32 {
return NullInt32{Int32, true}
}
// MarshalJSON method is called by json.Marshal,
// whenever it is of type NullInt32
func (ni NullInt32) MarshalJSON() ([]byte, error) {
if !ni.Valid {
return json.Marshal(nil)
}
return json.Marshal(ni.Int32)
}
// UnmarshalJSON method is called by json.Unmarshal,
// whenever it is of type NullInt32
func (ni *NullInt32) UnmarshalJSON(b []byte) error {
var i *int32
if err := json.Unmarshal(b, &i); err != nil {
return err
}
if i != nil {
ni.Valid = true
ni.Int32 = *i
} else {
ni.Valid = false
}
return nil
}
// Scan satisfies the sql.scanner interface
func (ni *NullInt32) Scan(value interface{}) error {
rt, ok := value.(int32)
if ok {
*ni = NullInt32{rt, true}
} else {
*ni = NullInt32{rt, false}
}
return nil
}
// Value satisfies the driver.Value interface
func (ni NullInt32) Value() (driver.Value, error) {
if ni.Valid {
return ni.Int32, nil
}
return nil, nil
}