-
-
Notifications
You must be signed in to change notification settings - Fork 13
/
string.go
77 lines (68 loc) · 1.7 KB
/
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package nulls
import (
"database/sql"
"database/sql/driver"
"encoding/json"
)
// String replaces sql.NullString with an implementation
// that supports proper JSON encoding/decoding.
type String sql.NullString
// Interface implements the nullable interface. It returns nil if
// the string is not valid, otherwise it returns the string value.
func (ns String) Interface() interface{} {
if !ns.Valid {
return nil
}
return ns.String
}
// NewString returns a new, properly instantiated
// String object.
func NewString(s string) String {
return String{String: s, Valid: true}
}
// Scan implements the Scanner interface.
func (ns *String) Scan(value interface{}) error {
n := sql.NullString{String: ns.String}
err := n.Scan(value)
ns.String, ns.Valid = n.String, n.Valid
return err
}
// Value implements the driver Valuer interface.
func (ns String) Value() (driver.Value, error) {
if !ns.Valid {
return nil, nil
}
return ns.String, nil
}
// MarshalJSON marshals the underlying value to a
// proper JSON representation.
func (ns String) MarshalJSON() ([]byte, error) {
if ns.Valid {
return json.Marshal(ns.String)
}
return json.Marshal(nil)
}
// UnmarshalJSON will unmarshal a JSON value into
// the propert representation of that value.
func (ns *String) UnmarshalJSON(text []byte) error {
ns.Valid = false
if string(text) == "null" {
return nil
}
if err := json.Unmarshal(text, &ns.String); err == nil {
ns.Valid = true
}
return nil
}
// UnmarshalText will unmarshal text value into
// the propert representation of that value.
func (ns *String) UnmarshalText(text []byte) error {
ns.Valid = false
t := string(text)
if t == "null" {
return nil
}
ns.String = t
ns.Valid = true
return nil
}