2021-09-27 08:36:28 +00:00
|
|
|
package conf
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"fmt"
|
|
|
|
"net"
|
2021-10-17 13:40:17 +00:00
|
|
|
"sort"
|
2021-10-11 09:46:40 +00:00
|
|
|
"strings"
|
2021-09-27 08:36:28 +00:00
|
|
|
)
|
|
|
|
|
2022-06-21 11:41:15 +00:00
|
|
|
// IPsOrCIDRs is a parameter that contains a list of IPs or CIDRs.
|
|
|
|
type IPsOrCIDRs []fmt.Stringer
|
2021-09-27 08:36:28 +00:00
|
|
|
|
2022-06-21 11:41:15 +00:00
|
|
|
// MarshalJSON implements json.Marshaler.
|
|
|
|
func (d IPsOrCIDRs) MarshalJSON() ([]byte, error) {
|
2021-09-27 08:36:28 +00:00
|
|
|
out := make([]string, len(d))
|
|
|
|
|
|
|
|
for i, v := range d {
|
2022-06-21 11:41:15 +00:00
|
|
|
out[i] = v.String()
|
2021-09-27 08:36:28 +00:00
|
|
|
}
|
|
|
|
|
2021-10-17 13:40:17 +00:00
|
|
|
sort.Strings(out)
|
|
|
|
|
2021-09-27 08:36:28 +00:00
|
|
|
return json.Marshal(out)
|
|
|
|
}
|
|
|
|
|
2022-06-21 11:41:15 +00:00
|
|
|
// UnmarshalJSON implements json.Unmarshaler.
|
|
|
|
func (d *IPsOrCIDRs) UnmarshalJSON(b []byte) error {
|
2021-10-11 09:46:40 +00:00
|
|
|
var in []string
|
|
|
|
if err := json.Unmarshal(b, &in); err != nil {
|
2021-09-27 08:36:28 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2021-10-11 09:46:40 +00:00
|
|
|
if len(in) == 0 {
|
2021-09-27 08:36:28 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2021-10-11 09:46:40 +00:00
|
|
|
for _, t := range in {
|
2021-09-27 08:36:28 +00:00
|
|
|
if _, ipnet, err := net.ParseCIDR(t); err == nil {
|
|
|
|
*d = append(*d, ipnet)
|
|
|
|
} else if ip := net.ParseIP(t); ip != nil {
|
|
|
|
*d = append(*d, ip)
|
|
|
|
} else {
|
2022-06-21 11:41:15 +00:00
|
|
|
return fmt.Errorf("unable to parse IP/CIDR '%s'", t)
|
2021-09-27 08:36:28 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
2021-10-11 09:46:40 +00:00
|
|
|
|
2022-06-21 11:41:15 +00:00
|
|
|
func (d *IPsOrCIDRs) unmarshalEnv(s string) error {
|
2021-10-11 09:46:40 +00:00
|
|
|
byts, _ := json.Marshal(strings.Split(s, ","))
|
|
|
|
return d.UnmarshalJSON(byts)
|
|
|
|
}
|