-
Notifications
You must be signed in to change notification settings - Fork 18
/
blob.go
92 lines (72 loc) · 1.69 KB
/
blob.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
86
87
88
89
90
91
92
// Copyright 2022 Fluidity Money. All rights reserved. Use of this
// source code is governed by a GPL-style license that can be found in the
// LICENSE.md file.
package misc
// blob contains byte arrays that should be implicitly coerced into base64
// on the wire and into the database
import (
sqlDriver "database/sql/driver"
"encoding/base64"
"encoding/json"
"fmt"
)
// Blob is the internal representation of a byte array that's encoded as
// a base64 string when on the wire and in the database
type Blob []byte
func (blob *Blob) UnmarshalJSON(b []byte) (err error) {
var str string
if err = json.Unmarshal(b, &str); err != nil {
return fmt.Errorf(
"Failed to unmarshal a JSON blob containing %v! %v",
b,
err,
)
}
*blob, err = base64.StdEncoding.DecodeString(str)
if err != nil {
return fmt.Errorf(
"Failed to decode a blob string of %v to base64! %v",
str,
err,
)
}
return
}
func (blob Blob) MarshalJSON() ([]byte, error) {
str := base64.StdEncoding.EncodeToString(blob)
bytes, err := json.Marshal(str)
if err != nil {
return nil, fmt.Errorf(
"Failed to marshal a blob to string! %v",
err,
)
}
return bytes, nil
}
func (blob Blob) Value() (sqlDriver.Value, error) {
return base64.StdEncoding.EncodeToString(blob), nil
}
func (blob *Blob) Scan(v interface{}) error {
if v == nil {
return nil
}
switch v.(type) {
case string:
var err error
*blob, err = base64.StdEncoding.DecodeString(v.(string))
if err != nil {
return fmt.Errorf(
"Failed to decode a string of %v as base64! %v",
v.(string),
err,
)
}
default:
return fmt.Errorf(
"Failed to scan type %T content %v into the Blob type!",
v,
v,
)
}
return nil
}