-
Notifications
You must be signed in to change notification settings - Fork 2
/
null_string.go
58 lines (52 loc) · 1.11 KB
/
null_string.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
package gosql
import (
"database/sql/driver"
"encoding/json"
)
// NullString holds an string value that might be null in the
// database.
type NullString struct {
String string
Valid bool
}
// Scan implements the Scanner interface.
func (n *NullString) Scan(value interface{}) error {
if value == nil {
n.Valid = false
return nil
}
switch value.(type) {
case string:
n.String, n.Valid = value.(string), true
case []byte:
n.String, n.Valid = string(value.([]byte)), true
}
return nil
}
// Value implements the driver Valuer interface.
func (n NullString) Value() (driver.Value, error) {
if !n.Valid {
return nil, nil
}
return n.String, nil
}
// MarshalJSON implements the Marshaler interface.
func (n NullString) MarshalJSON() ([]byte, error) {
if n.Valid {
return json.Marshal(n.String)
}
return json.Marshal(nil)
}
// UnmarshalJSON implements the Unmarshaler interface.
func (n *NullString) UnmarshalJSON(data []byte) error {
var s *string
if err := json.Unmarshal(data, &s); err != nil {
return err
}
if s != nil {
n.String, n.Valid = *s, true
} else {
n.Valid = false
}
return nil
}