This repository was archived by the owner on Dec 13, 2017. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathnull.go
More file actions
70 lines (57 loc) · 1.3 KB
/
null.go
File metadata and controls
70 lines (57 loc) · 1.3 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
package shopy
import (
"database/sql"
"encoding/json"
)
// NullInt64 is a wraper for sql.NullInt64 that works with JSON Unmarshal
type NullInt64 struct {
sql.NullInt64
}
// MarshalJSON wraps the json.Marshal function
func (v NullInt64) MarshalJSON() ([]byte, error) {
if v.Valid {
return json.Marshal(v.Int64)
}
return json.Marshal(nil)
}
// UnmarshalJSON wraps the json.Unmarshal function
func (v *NullInt64) UnmarshalJSON(data []byte) error {
// Unmarshalling into a pointer will let us detect null
var x *int64
if err := json.Unmarshal(data, &x); err != nil {
return err
}
if x != nil {
v.Valid = true
v.Int64 = *x
} else {
v.Valid = false
}
return nil
}
// NullString is a wraper for sql.NullString that works with JSON Unmarshal
type NullString struct {
sql.NullString
}
// MarshalJSON wraps the json.Marshal function
func (v NullString) MarshalJSON() ([]byte, error) {
if v.Valid {
return json.Marshal(v.String)
}
return json.Marshal(nil)
}
// UnmarshalJSON wraps the json.Unmarshal function
func (v *NullString) UnmarshalJSON(data []byte) error {
// Unmarshalling into a pointer will let us detect null
var x *string
if err := json.Unmarshal(data, &x); err != nil {
return err
}
if x != nil {
v.Valid = true
v.String = *x
} else {
v.Valid = false
}
return nil
}