-
Notifications
You must be signed in to change notification settings - Fork 0
/
json_ip.go
45 lines (37 loc) · 896 Bytes
/
json_ip.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
package kittycad
import (
"bytes"
"net/netip"
"strings"
)
// IP is a wrapper around ip.IP which marshals to and from empty strings.
type IP struct {
*netip.Addr
}
// MarshalJSON implements the json.Marshaler interface.
func (u IP) MarshalJSON() ([]byte, error) {
return u.MarshalText()
}
func (u IP) String() string {
return u.String()
}
// UnmarshalJSON implements the json.Unmarshaler interface.
// The time is expected to be a quoted string in RFC 3339 format.
func (u *IP) 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
}
ip, err := netip.ParseAddr(strings.Trim(string(data), `"`))
if err != nil {
return err
}
*u = IP{&ip}
return
}