Add Custom IPNet Json Marshaling

This commit is contained in:
Samuel Lorch 2023-03-03 11:28:38 +01:00
parent d604ba1074
commit d70a888b56
2 changed files with 31 additions and 2 deletions

View file

@ -2,7 +2,6 @@ package definitions
import (
"encoding/json"
"net"
"net/netip"
"go4.org/netipx"
@ -13,7 +12,7 @@ type Address struct {
Comment string `json:"comment,omitempty"`
Host *netip.Addr `json:"host,omitempty"`
Range *netipx.IPRange `json:"range,omitempty"`
Network *net.IPNet `json:"network,omitempty"`
Network *IPNet `json:"network,omitempty"`
Children *[]string `json:"children,omitempty"`
}

30
pkg/definitions/ipnet.go Normal file
View file

@ -0,0 +1,30 @@
package definitions
import (
"encoding/json"
"net"
)
type IPNet struct {
net.IPNet
}
// MarshalJSON for IPNet
func (i IPNet) MarshalJSON() ([]byte, error) {
return json.Marshal(i.String())
}
// UnmarshalJSON for IPNet
func (i *IPNet) UnmarshalJSON(b []byte) error {
var s string
if err := json.Unmarshal(b, &s); err != nil {
return err
}
_, ipnet, err := net.ParseCIDR(s)
if err != nil {
return err
}
i.IPNet = *ipnet
return nil
}