Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 16 additions & 4 deletions ip_slice.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,23 +70,35 @@ func (s *ipSliceValue) String() string {
return "[" + out + "]"
}

func (s *ipSliceValue) fromString(val string) net.IP {
return net.ParseIP(strings.TrimSpace(val))
func (s *ipSliceValue) fromString(val string) (net.IP, error) {
ip := net.ParseIP(strings.TrimSpace(val))
if ip == nil {
return nil, fmt.Errorf("invalid string being converted to IP address: %s", val)
}
return ip, nil
}

func (s *ipSliceValue) toString(val net.IP) string {
return val.String()
}

func (s *ipSliceValue) Append(val string) error {
*s.value = append(*s.value, s.fromString(val))
ip, err := s.fromString(val)
if err != nil {
return err
}
*s.value = append(*s.value, ip)
return nil
}

func (s *ipSliceValue) Replace(val []string) error {
out := make([]net.IP, len(val))
for i, d := range val {
out[i] = s.fromString(d)
ip, err := s.fromString(d)
if err != nil {
return err
}
out[i] = ip
}
*s.value = out
return nil
Expand Down
38 changes: 38 additions & 0 deletions ip_slice_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -243,3 +243,41 @@ func TestIPSBadQuoting(t *testing.T) {
}
}
}

func TestIPSliceValueRejectsInvalidIPs(t *testing.T) {
for _, operation := range []string{"Append", "Replace"} {
t.Run(operation, func(t *testing.T) {
var ips []net.IP
value := newIPSliceValue([]net.IP{net.ParseIP("192.0.2.1")}, &ips)
var err error
if operation == "Append" {
err = value.Append("not-an-ip")
} else {
err = value.Replace([]string{"2001:db8::1", "not-an-ip"})
}
if err == nil {
t.Error("expected an error for an invalid IP")
}
if len(ips) != 1 || !ips[0].Equal(net.ParseIP("192.0.2.1")) {
t.Errorf("invalid input changed the slice: %v", ips)
}
})
}
}

func TestIPSliceValueAppendAndReplace(t *testing.T) {
var ips []net.IP
value := newIPSliceValue(nil, &ips)
if err := value.Append(" 192.0.2.1 "); err != nil {
t.Fatal(err)
}
if len(ips) != 1 || !ips[0].Equal(net.ParseIP("192.0.2.1")) {
t.Fatalf("unexpected appended IPs: %v", ips)
}
if err := value.Replace([]string{" 2001:db8::1 "}); err != nil {
t.Fatal(err)
}
if len(ips) != 1 || !ips[0].Equal(net.ParseIP("2001:db8::1")) {
t.Fatalf("unexpected replacement IPs: %v", ips)
}
}
Loading