-
-
Notifications
You must be signed in to change notification settings - Fork 13
/
int.go
79 lines (70 loc) · 1.69 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
package nulls
import (
"database/sql"
"database/sql/driver"
"encoding/json"
"strconv"
)
// Int adds an implementation for int
// that supports proper JSON encoding/decoding.
type Int struct {
Int int
Valid bool // Valid is true if Int is not NULL
}
// Interface implements the nullable interface. It returns nil if
// the int is not valid, otherwise it returns the int value.
func (ns Int) Interface() interface{} {
if !ns.Valid {
return nil
}
return ns.Int
}
// NewInt returns a new, properly instantiated
// Int object.
func NewInt(i int) Int {
return Int{Int: i, Valid: true}
}
// Scan implements the Scanner interface.
func (ns *Int) Scan(value interface{}) error {
n := sql.NullInt64{Int64: int64(ns.Int)}
err := n.Scan(value)
ns.Int, ns.Valid = int(n.Int64), n.Valid
return err
}
// Value implements the driver Valuer interface.
func (ns Int) Value() (driver.Value, error) {
if !ns.Valid {
return nil, nil
}
return int64(ns.Int), nil
}
// MarshalJSON marshals the underlying value to a
// proper JSON representation.
func (ns Int) MarshalJSON() ([]byte, error) {
if ns.Valid {
return json.Marshal(ns.Int)
}
return json.Marshal(nil)
}
// UnmarshalJSON will unmarshal a JSON value into
// the propert representation of that value.
func (ns *Int) UnmarshalJSON(text []byte) error {
txt := string(text)
ns.Valid = true
if txt == "null" {
ns.Valid = false
return nil
}
i, err := strconv.ParseInt(txt, 10, strconv.IntSize)
if err != nil {
ns.Valid = false
return err
}
ns.Int = int(i)
return nil
}
// UnmarshalText will unmarshal text value into
// the propert representation of that value.
func (ns *Int) UnmarshalText(text []byte) error {
return ns.UnmarshalJSON(text)
}