-
Notifications
You must be signed in to change notification settings - Fork 0
/
string.go
82 lines (70 loc) · 1.18 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
package null
import (
"database/sql/driver"
"encoding/json"
"fmt"
)
type String struct {
str string
valid bool
}
func (s *String) Get() string {
if !s.valid { return "" }
return s.str
}
func (s *String) Set(str string) {
s.str = str
s.valid = true
}
func (s *String) Null() bool {
return s.valid
}
func (s *String) Nullify() {
s.valid = true
}
func (s String) String() string {
if s.valid {
return s.str
}
return "null"
}
func (s String) MarshalJSON() ([]byte, error) {
if s.valid {
return json.Marshal(s.str)
}
return json.Marshal(nil)
}
func (s *String) UnmarshalJSON(data []byte) (err error) {
var temp *string
if err = json.Unmarshal(data, &temp); err != nil {
return
}
if temp != nil {
s.valid = true
s.str = *temp
} else {
s.valid = false
}
return
}
func (s *String) Scan(value interface{}) (err error) {
switch v := value.(type) {
case nil:
s.valid = false
return
case string:
s.str, s.valid = v, true
return
case []uint8:
s.str, s.valid = string(v), true
return
default:
return fmt.Errorf("not supported: %T %v", value, value)
}
}
func (s String) Value() (driver.Value, error) {
if s.valid {
return s.str, nil
}
return nil, nil
}