-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathipaddress.go
133 lines (114 loc) · 2.43 KB
/
ipaddress.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
package marshallable
import (
"encoding/json"
"errors"
"net"
)
var ErrInvalidIP = errors.New("invalid IP")
type IP struct {
net.IP
}
// String returns the IP as a string.
func (ip IP) String() string {
if ip.IP == nil {
return "0.0.0.0"
}
return ip.IP.String()
}
// MarshalJSON implements the json.Marshaler interface.
func (ip IP) MarshalJSON() ([]byte, error) {
return json.Marshal(ip.String())
}
// UnmarshalJSON implements the json.Unmarshaler interface.
func (ip *IP) UnmarshalJSON(data []byte) (err error) {
var value string
err = json.Unmarshal(data, &value)
if err != nil {
return
}
ip.IP = net.ParseIP(value)
if ip.IP == nil {
err = ErrInvalidIP
}
return
}
// MustIP returns the IP or panics.
func MustIP(value string) IP {
ip := net.ParseIP(value)
if ip == nil {
panic(ErrInvalidIP)
}
return IP{ip}
}
var ErrInvalidIPv4 = errors.New("invalid IPv4")
type IPv4 struct {
net.IP
}
// String returns the IP as a string.
func (ip IPv4) String() string {
if ip.IP == nil {
return "0.0.0.0"
}
return ip.IP.String()
}
// MarshalJSON implements the json.Marshaler interface.
func (ip IPv4) MarshalJSON() ([]byte, error) {
return json.Marshal(ip.IP.String())
}
// UnmarshalJSON implements the json.Unmarshaler interface.
func (ip *IPv4) UnmarshalJSON(data []byte) (err error) {
var value string
err = json.Unmarshal(data, &value)
if err != nil {
return
}
ip.IP = net.ParseIP(value)
if ip.IP.To4() == nil {
err = ErrInvalidIPv4
}
return
}
// MustIPv4 returns the IPv4 or panics.
func MustIPv4(value string) IPv4 {
ip := net.ParseIP(value)
if ip.To4() == nil {
panic(ErrInvalidIP)
}
return IPv4{ip}
}
var ErrInvalidIPv6 = errors.New("invalid IPv6")
type IPv6 struct {
net.IP
}
// String returns the IP as a string.
func (ip IPv6) String() string {
if ip.IP == nil {
return "0:0:0:0:0:0:0:0"
}
return ip.IP.String()
}
// MarshalJSON implements the json.Marshaler interface.
func (ip IPv6) MarshalJSON() ([]byte, error) {
return json.Marshal(ip.IP.String())
}
// UnmarshalJSON implements the json.Unmarshaler interface.
func (ip *IPv6) UnmarshalJSON(data []byte) (err error) {
var value string
err = json.Unmarshal(data, &value)
if err != nil {
return
}
ip.IP = net.ParseIP(value)
if ip.IP.To16() == nil {
err = ErrInvalidIPv6
}
return
}
// MustIPv6 returns the IPv6 or panics.
func MustIPv6(value string) IPv6 {
ip := net.ParseIP(value)
if ip.To16() == nil {
panic(ErrInvalidIP)
}
return IPv6{ip}
}