forked from Cyphrme/Coz
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbase64.go
More file actions
58 lines (50 loc) · 1.77 KB
/
base64.go
File metadata and controls
58 lines (50 loc) · 1.77 KB
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
package coze
import (
"encoding/base64"
"fmt"
"strings"
)
// Type B64 is a Coze addition to Go's base64. B64 is useful for marshaling and
// unmarshalling structs. B64's underlying type is []byte and is represented in
// JSON as base64 URI truncated (b64ut).
//
// When converting integers or other types to B64, `nil` is encoded as "" and
// zero is encoded as "AA".
type B64 []byte
// UnmarshalJSON implements JSON.UnmarshalJSON so B64 is encoded as b64ut.
func (t *B64) UnmarshalJSON(b []byte) error {
// JSON.Unmarshal gives b encapsulated in quote characters. Quotes characters
// are invalid base64 and must be stripped.
s, err := base64.URLEncoding.WithPadding(base64.NoPadding).DecodeString(strings.Trim(string(b), "\""))
if err != nil {
return err
}
*t = B64(s)
return nil
}
// MarshalJSON implements JSON.MarshalJSON so B64 is decoded from b64ut. Error
// is always nil.
func (t B64) MarshalJSON() ([]byte, error) {
// JSON expects stings to be wrapped with double quote character.
return []byte(fmt.Sprintf("\"%v\"", t)), nil
}
// String implements fmt.Stringer. Use with `%s`, `%v`, `%+v`.
func (t B64) String() string {
return base64.URLEncoding.WithPadding(base64.NoPadding).EncodeToString([]byte(t))
}
// GoString implements fmt.GoStringer. Use with `%#v` (not %s or %+v).
func (t B64) GoString() string {
return base64.URLEncoding.WithPadding(base64.NoPadding).EncodeToString([]byte(t))
}
// Decode decodes a base64 string to B64.
func Decode(b64 string) (B64, error) {
return base64.URLEncoding.WithPadding(base64.NoPadding).DecodeString(b64)
}
// MustDecode decodes a base64 string to B64. Will panic on error.
func MustDecode(b64 string) B64 {
b, err := base64.URLEncoding.WithPadding(base64.NoPadding).DecodeString(b64)
if err != nil {
panic(err)
}
return b
}