-
Notifications
You must be signed in to change notification settings - Fork 1
/
json_url.go
54 lines (44 loc) · 1.04 KB
/
json_url.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
package kittycad
import (
"bytes"
"net/url"
"strings"
)
// URL is a wrapper around url.URL which marshals to and from empty strings.
type URL struct {
*url.URL
}
// MarshalJSON implements the json.Marshaler interface.
func (u URL) MarshalJSON() ([]byte, error) {
if u.URL == nil {
return []byte("null"), nil
}
return []byte(`"` + u.URL.String() + `"`), nil
}
func (u URL) String() string {
if u.URL == nil {
return ""
}
return u.URL.String()
}
// UnmarshalJSON implements the json.Unmarshaler interface.
// The time is expected to be a quoted string in RFC 3339 format.
func (u *URL) 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
}
// Fractional seconds are handled implicitly by Parse.
uu, err := url.Parse(strings.Trim(string(data), `"`))
if err != nil {
return err
}
*u = URL{uu}
return
}