-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathjson_base64.go
56 lines (45 loc) · 1.23 KB
/
json_base64.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
package kittycad
import (
"bytes"
"encoding/base64"
"strings"
)
// Base64 is a wrapper around url.Base64 which marshals to and from empty strings.
type Base64 struct {
Inner []byte
}
// MarshalJSON implements the json.Marshaler interface.
func (u Base64) MarshalJSON() ([]byte, error) {
if u.Inner == nil || len(u.Inner) <= 0 {
return []byte("null"), nil
}
return []byte(`"` + base64.RawURLEncoding.EncodeToString(u.Inner) + `"`), nil
}
func (u Base64) String() string {
if u.Inner == nil {
return ""
}
return base64.RawURLEncoding.EncodeToString(u.Inner)
}
// UnmarshalJSON implements the json.Unmarshaler interface.
// The time is expected to be a quoted string in RFC 3339 format.
func (u *Base64) UnmarshalJSON(data []byte) (err error) {
// By convention, unmarshalers implement UnmarshalJSON([]byte("null")) as a no-op.
if bytes.Equal(data, []byte("null")) {
return nil
}
if bytes.Equal(data, []byte("")) {
return nil
}
if bytes.Equal(data, []byte(`""`)) {
return nil
}
sdata := string(data)
// Fractional seconds are handled implicitly by Parse.
uu, err := base64.RawURLEncoding.DecodeString(strings.TrimRight(strings.Trim(sdata, `"`), "="))
if err != nil {
return err
}
*u = Base64{Inner: uu}
return
}