-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbyte_slice.go
65 lines (58 loc) · 1.44 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
package nulls
import (
"database/sql"
"database/sql/driver"
"encoding/base64"
"encoding/json"
)
// ByteSlice holds a nullable byte slice.
type ByteSlice struct {
// ByteSlice is the actual byte slice when Valid.
ByteSlice []byte `exhaustruct:"optional"`
// Valid when no NULL-value is represented.
Valid bool
}
// NewByteSlice returns a valid ByteSlice with the given value.
func NewByteSlice(b []byte) ByteSlice {
return ByteSlice{
ByteSlice: b,
Valid: true,
}
}
// MarshalJSON marshals the ByteSlice. If not valid, a NULL-value is returned.
func (b ByteSlice) MarshalJSON() ([]byte, error) {
if !b.Valid {
return json.Marshal(nil)
}
return json.Marshal(b.ByteSlice)
}
// UnmarshalJSON as byte slice or sets Valid to false if null.
func (b *ByteSlice) UnmarshalJSON(data []byte) error {
if isNull(data) {
b.Valid = false
return nil
}
b.Valid = true
return json.Unmarshal(data, &b.ByteSlice)
}
// Scan to byte slice value or not valid if nil.
func (b *ByteSlice) Scan(src any) error {
var sqlString sql.NullString
err := sqlString.Scan(src)
if err != nil {
return err
}
b.Valid = sqlString.Valid
b.ByteSlice, err = base64.StdEncoding.DecodeString(sqlString.String)
if err != nil {
return err
}
return nil
}
// Value returns the value for satisfying the driver.Valuer interface.
func (b ByteSlice) Value() (driver.Value, error) {
if !b.Valid {
return nil, nil
}
return base64.StdEncoding.EncodeToString(b.ByteSlice), nil
}