From d9ecfae454d036dff8e95f07c7c89802cc8db2c0 Mon Sep 17 00:00:00 2001 From: Samuel Lorch Date: Sat, 8 Apr 2023 01:36:20 +0200 Subject: [PATCH] Fix Address Type --- internal/definitions/interface.go | 2 +- internal/definitions/ipcidr.go | 32 +++++++++++++++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) create mode 100644 internal/definitions/ipcidr.go diff --git a/internal/definitions/interface.go b/internal/definitions/interface.go index 97e1de9..11f4e44 100644 --- a/internal/definitions/interface.go +++ b/internal/definitions/interface.go @@ -8,7 +8,7 @@ type Interface struct { Alias string `json:"alias,omitempty" validate:"min=0,max=3"` Type InterfaceType `json:"type" validate:"min=0,max=3"` AddressingMode InterfaceAddressingMode `json:"addressing_mode" validate:"min=0,max=2"` - Address *IPNet `json:"address,omitempty" validate:"excluded_unless=AddressingMode 1"` + Address *IPCIDR `json:"address,omitempty" validate:"excluded_unless=AddressingMode 1"` HardwareInterface *string `json:"hardware_interface,omitempty"` // TODO fix Validator for int pointers with min=0,max=4094 VlanID *uint `json:"vlan_id,omitempty"` diff --git a/internal/definitions/ipcidr.go b/internal/definitions/ipcidr.go new file mode 100644 index 0000000..480ef07 --- /dev/null +++ b/internal/definitions/ipcidr.go @@ -0,0 +1,32 @@ +package definitions + +import ( + "encoding/json" + "net" +) + +// IPCIDR is IP Address with the mask in CIDR format +type IPCIDR struct { + net.IPNet +} + +// MarshalJSON for IPCIDR +func (i IPCIDR) MarshalJSON() ([]byte, error) { + return json.Marshal(i.String()) +} + +// UnmarshalJSON for IPCIDR +func (i *IPCIDR) UnmarshalJSON(b []byte) error { + var s string + if err := json.Unmarshal(b, &s); err != nil { + return err + } + + ip, ipnet, err := net.ParseCIDR(s) + if err != nil { + return err + } + i.IPNet = *ipnet + i.IPNet.IP = ip + return nil +}