-
Notifications
You must be signed in to change notification settings - Fork 2
/
base64_string.go
85 lines (69 loc) · 1.52 KB
/
base64_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
82
83
84
85
package types
import (
"database/sql/driver"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
)
type Base64String []byte
func (self *Base64String) UnmarshalJSON(data []byte) error {
var s string
err := json.Unmarshal(data, &s)
if err != nil {
return err
}
return self.Decode(s)
}
func (self *Base64String) Unmarshal(buf []byte) error {
copy(*self, buf)
return nil
}
func (self *Base64String) Decode(s string) error {
// Decode base64
b, err := base64.RawURLEncoding.DecodeString(s)
if err != nil {
return err
}
*self = []byte(b)
return nil
}
func (self Base64String) MarshalJSON() (out []byte, err error) {
s := base64.RawURLEncoding.EncodeToString([]byte(self))
return json.Marshal(s)
}
func (self *Base64String) MarshalTo(buf []byte) (n int, err error) {
if len(buf) < len(*self) {
return 0, errors.New("buffer too small")
}
n = copy(buf, *self)
return
}
func (self *Base64String) Scan(src interface{}) error {
switch v := src.(type) {
case string:
return self.Decode(v)
default:
return fmt.Errorf("unsupported source type")
}
}
func (self Base64String) Size() int {
return len(self)
}
func (self Base64String) Value() (driver.Value, error) {
return self.Base64(), nil
}
func (self Base64String) Bytes() []byte {
return []byte(self)
}
func (self Base64String) Base64() string {
return base64.RawURLEncoding.EncodeToString([]byte(self))
}
func (self Base64String) Head(i int) []byte {
if i <= len(self) {
return []byte(self)[:i]
}
// Pad with zeros
i = len(self)
return []byte(self)[:i]
}