forked from drone/go-scm
-
Notifications
You must be signed in to change notification settings - Fork 86
/
string.go
49 lines (44 loc) · 1.11 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
// Copyright (c) 2014, Greg Roseberry
// All rights reserved.
package null
import (
"database/sql"
"encoding/json"
"fmt"
"reflect"
)
// String is a nullable string. It supports SQL and JSON
// serialization. It will marshal to null if null. Blank
// string input will be considered null.
type String struct {
sql.NullString
}
// UnmarshalJSON implements json.Unmarshaler.
// It supports string and null input. Blank string input
// does not produce a null String. It also supports
// unmarshalling a sql.NullString.
func (s *String) UnmarshalJSON(data []byte) error {
var err error
var v interface{}
if err = json.Unmarshal(data, &v); err != nil {
return err
}
switch x := v.(type) {
case string:
s.String = x
case map[string]interface{}:
err = json.Unmarshal(data, &s.NullString)
case nil:
s.Valid = false
return nil
default:
err = fmt.Errorf("json: cannot unmarshal %v into Go value of type null.String", reflect.TypeOf(v).Name())
}
s.Valid = err == nil
return err
}
// IsZero returns true for null strings, for potential
// future omitempty support.
func (s String) IsZero() bool {
return !s.Valid
}