-
-
Notifications
You must be signed in to change notification settings - Fork 10
/
string.go
85 lines (73 loc) · 1.6 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
78
79
80
81
82
83
84
85
package nulltype
import (
"database/sql"
"database/sql/driver"
"encoding/json"
)
// NullString is null friendly type for string.
type NullString struct {
s sql.NullString
}
// NullStringOf return NullString that the value is set.
func NullStringOf(value string) NullString {
var s NullString
s.Set(value)
return s
}
// Valid return the value is valid. If true, it is not null value.
func (s *NullString) Valid() bool {
return s.s.Valid
}
// StringValue return the value.
func (s *NullString) StringValue() string {
return s.s.String
}
// Reset set nil to the value.
func (s *NullString) Reset() {
s.s.String = ""
s.s.Valid = false
}
// Set set the value.
func (s *NullString) Set(value string) {
s.s.Valid = true
s.s.String = value
}
// Scan is a method for database/sql.
func (s *NullString) Scan(value interface{}) error {
return s.s.Scan(value)
}
// String return string indicated the value.
func (s NullString) String() string {
if !s.s.Valid {
return ""
}
return s.s.String
}
// MarshalJSON encode the value to JSON.
func (s NullString) MarshalJSON() ([]byte, error) {
if !s.s.Valid {
return []byte("null"), nil
}
return json.Marshal(s.s.String)
}
// UnmarshalJSON decode data to the value.
func (s *NullString) UnmarshalJSON(data []byte) error {
var value *string
if err := json.Unmarshal(data, &value); err != nil {
return err
}
s.s.Valid = value != nil
if value == nil {
s.s.String = ""
} else {
s.s.String = *value
}
return nil
}
// Value implement driver.Valuer.
func (s NullString) Value() (driver.Value, error) {
if !s.Valid() {
return nil, nil
}
return s.s.String, nil
}