-
-
Notifications
You must be signed in to change notification settings - Fork 13
/
byte_slice.go
79 lines (69 loc) · 1.91 KB
/
byte_slice.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
package nulls
import (
"database/sql"
"database/sql/driver"
"encoding/base64"
"encoding/json"
)
// ByteSlice adds an implementation for []byte
// that supports proper JSON encoding/decoding.
type ByteSlice struct {
ByteSlice []byte
Valid bool // Valid is true if ByteSlice is not NULL
}
// Interface implements the nullable interface. It returns nil if
// the byte slice is not valid, otherwise it returns the byte slice value.
func (ns ByteSlice) Interface() interface{} {
if !ns.Valid {
return nil
}
return ns.ByteSlice
}
// NewByteSlice returns a new, properly instantiated
// ByteSlice object.
func NewByteSlice(b []byte) ByteSlice {
return ByteSlice{ByteSlice: b, Valid: true}
}
// Scan implements the Scanner interface.
func (ns *ByteSlice) Scan(value interface{}) error {
n := sql.NullString{String: base64.StdEncoding.EncodeToString(ns.ByteSlice)}
err := n.Scan(value)
if err != nil {
return err
}
//ns.Float32, ns.Valid = float32(n.Float64), n.Valid
ns.ByteSlice, err = base64.StdEncoding.DecodeString(n.String)
ns.Valid = n.Valid
return err
}
// Value implements the driver Valuer interface.
func (ns ByteSlice) Value() (driver.Value, error) {
if !ns.Valid {
return nil, nil
}
return base64.StdEncoding.EncodeToString(ns.ByteSlice), nil
}
// MarshalJSON marshals the underlying value to a
// proper JSON representation.
func (ns ByteSlice) MarshalJSON() ([]byte, error) {
if ns.Valid {
return json.Marshal(ns.ByteSlice)
}
return json.Marshal(nil)
}
// UnmarshalJSON will unmarshal a JSON value into
// the propert representation of that value.
func (ns *ByteSlice) UnmarshalJSON(text []byte) error {
ns.Valid = false
if string(text) == "null" {
return nil
}
ns.ByteSlice = text
ns.Valid = true
return nil
}
// UnmarshalText will unmarshal text value into
// the propert representation of that value.
func (ns *ByteSlice) UnmarshalText(text []byte) error {
return ns.UnmarshalJSON(text)
}