Skip to content

Commit

Permalink
add more informative error for empty values (#40)
Browse files Browse the repository at this point in the history
  • Loading branch information
lstmux authored Jan 10, 2024
1 parent 800e064 commit 48b6bc9
Show file tree
Hide file tree
Showing 5 changed files with 9 additions and 5 deletions.
4 changes: 3 additions & 1 deletion ip/ip.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ import (
"fmt"
)

var ErrEmptyValue = errors.New("ip address cannot be empty")

type IP struct {
v4 IPv4
v6 IPv6
Expand Down Expand Up @@ -84,7 +86,7 @@ func (ip IP) IsIPv6() bool {

func FromString(value string) (IP, error) {
if value == "" {
return IP{}, fmt.Errorf("empty value")
return IP{}, ErrEmptyValue
}

var v4Addr, err = V4FromString(value)
Expand Down
3 changes: 2 additions & 1 deletion ip/ip_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ func TestIP_Value(t *testing.T) {
name: "IPv6",
ip: IP{
isV6: true,
v6: IPv6("2001:0db8:85a3:0000:0000:8a2e:0370:7334"),
v6: IPv6("2001:db8:85a3::8a2e:370:7334"),
raw: "2001:0db8:85a3:0000:0000:8a2e:0370:7334",
},
wantValue: "2001:0db8:85a3:0000:0000:8a2e:0370:7334",
Expand Down Expand Up @@ -302,6 +302,7 @@ func TestParseIPFromString(t *testing.T) {
t.Errorf("ParseIPFromString() error = %v, wantErr %v", err, tt.wantErr)
return
}

if got != tt.wantValue {
t.Errorf("ParseIPFromString() got = %v, want %v", got, tt.wantValue)
}
Expand Down
2 changes: 1 addition & 1 deletion ip/ip_v4.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ func (ip IPv4) String() string {

func V4FromString(value string) (IPv4, error) {
if value == "" {
return "", fmt.Errorf("empty value")
return "", ErrEmptyValue
}

var addr, err = netip.ParseAddr(value)
Expand Down
2 changes: 1 addition & 1 deletion ip/ip_v6.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ func (ip IPv6) String() string {

func V6FromString(value string) (IPv6, error) {
if value == "" {
return "", fmt.Errorf("empty value")
return "", ErrEmptyValue
}

var addr, err = netip.ParseAddr(value)
Expand Down
3 changes: 2 additions & 1 deletion ip/ip_v6_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package ip
import (
"database/sql/driver"
"encoding/json"
"fmt"
"reflect"
"testing"
)
Expand Down Expand Up @@ -83,7 +84,7 @@ func TestIPv6_UnmarshalJSON(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var ipv6 IPv6
err := json.Unmarshal([]byte(tt.ip), &ipv6)
err := json.Unmarshal([]byte(fmt.Sprintf(`"%s"`, tt.ip)), &ipv6)
if (err != nil) != tt.wantErr {
t.Errorf("UnmarshalJSON() error = %v, wantErr %v", err, tt.wantErr)
}
Expand Down

0 comments on commit 48b6bc9

Please sign in to comment.