forked from gobuffalo/pop
-
Notifications
You must be signed in to change notification settings - Fork 0
/
string.go
62 lines (54 loc) · 1.29 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
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
func (ns String) Interface() interface{} {
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
}
s := ""
err := json.Unmarshal(text, &s)
if err == nil {
ns.String = s
ns.Valid = true
}
return err
}