-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstring.go
53 lines (47 loc) · 1.21 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
package nulls
import (
"database/sql"
"encoding/json"
"fmt"
"reflect"
)
// String is a possibly invalid string type.
type String struct {
sql.NullString
}
// ValidString returns a new String that is valid.
func ValidString(value string) String {
return String{sql.NullString{String: value, Valid: true}}
}
// InvalidString returns a new String that is invalid.
func InvalidString() String {
return String{sql.NullString{String: "", Valid: false}}
}
// MarshalJSON converts a String to JSON. It returns the value if valid and
// null otherwise.
func (null String) MarshalJSON() ([]byte, error) {
if null.Valid {
return json.Marshal(null.String)
}
return []byte("null"), nil
}
// UnmarshalJSON converts JSON to a String. Nil input returns an invalid
// String, otherwise it returns a valid NullString.
func (null *String) UnmarshalJSON(data []byte) error {
// Unmarshal
var value interface{}
if err := json.Unmarshal(data, &value); err != nil {
return err
}
switch value.(type) {
case string:
null.String = value.(string)
null.Valid = true
case nil:
null.String = ""
null.Valid = false
default:
return fmt.Errorf("Cannot unmarshal %v into sql.NullString", reflect.TypeOf(value).Name())
}
return nil
}