-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathstring.go
64 lines (57 loc) · 1.2 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
package nulltypes
import (
"database/sql/driver"
"encoding/json"
)
// NullString is a wrapper around string
type NullString struct {
String string
Valid bool
}
// String method to get NullString object from string
func String(s string) NullString {
return NullString{
String: s,
Valid: true,
}
}
// MarshalJSON method is called by json.Marshal,
// whenever it is of type NullString
func (ns NullString) MarshalJSON() ([]byte, error) {
if !ns.Valid {
return json.Marshal(nil)
}
return json.Marshal(ns.String)
}
// UnmarshalJSON method is called by json.Unmarshal,
// whenever it is of type NullString
func (ns *NullString) UnmarshalJSON(b []byte) error {
var s *string
if err := json.Unmarshal(b, &s); err != nil {
return err
}
if s != nil {
ns.Valid = true
ns.String = *s
} else {
ns.Valid = false
}
return nil
}
// Scan satisfies the sql.scanner interface
func (ns *NullString) Scan(value interface{}) error {
rt, ok := value.(string)
if ok {
*ns = NullString{rt, true}
} else {
*ns = NullString{"", false}
}
return nil
}
// Value satisfies the driver.Value interface
func (ns NullString) Value() (driver.Value, error) {
if ns.Valid {
return ns.String, nil
}
return nil, nil
}