-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnullstring.go
49 lines (42 loc) · 879 Bytes
/
nullstring.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
package nullable
import (
"database/sql/driver"
"encoding/json"
"fmt"
)
// NullString MarshalJSON ignores ""
type NullString struct {
String string
Valid bool
}
func (ns *NullString) Scan(value interface{}) error {
if value == nil {
ns.String, ns.Valid = "", false
return nil
}
ns.Valid = true
// TODO review and check perfomance with PGX
ns.String = fmt.Sprintf("%v", value)
return nil
}
func (ns NullString) Value() (driver.Value, error) {
if !ns.Valid || len(ns.String) == 0 {
return "", nil
}
return ns.String, nil
}
func (ns NullString) MarshalJSON() ([]byte, error) {
if ns.Valid && ns.String != "" {
return json.Marshal(ns.String)
}
return []byte("null"), nil
}
func (ns *NullString) UnmarshalJSON(b []byte) error {
var s string
if err := json.Unmarshal(b, &s); err != nil {
return err
}
ns.String = s
ns.Valid = true
return nil
}