add IPVersion type to properly parse a 4 or 6

This commit is contained in:
Gibheer 2021-05-21 17:49:24 +02:00
parent d746ad7ac0
commit 08808fe984
1 changed files with 16 additions and 0 deletions

View File

@ -5,6 +5,7 @@ import (
"database/sql/driver"
"fmt"
"net"
"strconv"
)
type (
@ -12,6 +13,8 @@ type (
Subnet net.IPNet
// IP is used to parse an IP parameter.
IP net.IP
// IPVersion represents the two IP versions currently in use.
IPVersion int
)
// UnmarshalJSON parses a value into a subnet.
@ -69,3 +72,16 @@ func (i *IP) UnmarshalJSON(in []byte) error {
*i = IP(ip)
return nil
}
// UnmarshalJSON parses the incoming version from json.
func (v *IPVersion) UnmarshalJSON(in []byte) error {
raw, err := strconv.Atoi(string(in))
if err != nil {
return fmt.Errorf("can't parse ip version: %#v", err)
}
if raw != 4 && raw != 6 {
return fmt.Errorf("only version 4 and 6 are supported")
}
*v = IPVersion(raw)
return nil
}