From 08808fe98448522b394c2b4fe04453ced54a4ea5 Mon Sep 17 00:00:00 2001 From: Gibheer Date: Fri, 21 May 2021 17:49:24 +0200 Subject: [PATCH] add IPVersion type to properly parse a 4 or 6 --- types/ip.go | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/types/ip.go b/types/ip.go index 1844d15..1ac8d27 100644 --- a/types/ip.go +++ b/types/ip.go @@ -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 +}