Skip to content

Commit

Permalink
distinguish missing port and other errors on parsing addr
Browse files Browse the repository at this point in the history
  • Loading branch information
semihbkgr committed Aug 16, 2023
1 parent fe649ca commit d2af6e8
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 4 deletions.
11 changes: 8 additions & 3 deletions internal/addr.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,12 @@ func ParseAddr(addr string) (string, int, error) {
return defaultHost, 0, nil
}
host, port, err := net.SplitHostPort(addr)
if err != nil { // return the address itself if port is missing in the address
return addr, 0, nil
if err != nil {
// returns the address itself if port is missing in the address
if addrErr, ok := err.(*net.AddrError); ok && addrErr.Err == "missing port in address" {
return addr, 0, nil
}
return host, 0, err
}
portInt, err := strconv.Atoi(port)
if err != nil {
Expand All @@ -40,7 +44,8 @@ func ParseAddr(addr string) (string, int, error) {
if host == "" || strings.TrimSpace(host) == "" {
host = defaultHost
}
if portInt < 0 { // port number must be positive value
if portInt < 0 {
// the port number must be positive value
return "", 0, fmt.Errorf("invalid port number: '%d'", portInt)
}
return host, portInt, nil
Expand Down
5 changes: 4 additions & 1 deletion internal/addr_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ package internal_test

import (
"fmt"
"net"
"testing"

"github.com/stretchr/testify/assert"
Expand All @@ -42,8 +43,10 @@ func TestParseAddr(t *testing.T) {
{Addr: "", Target: parseAddrTarget{Host: "127.0.0.1", Port: 0, Err: nil}},
{Addr: "169.254.172.39", Target: parseAddrTarget{Host: "169.254.172.39", Port: 0, Err: nil}},
{Addr: "169.254.172.39:5703", Target: parseAddrTarget{Host: "169.254.172.39", Port: 5703, Err: nil}},
{Addr: "fe80::43:ecff:fec9:1683", Target: parseAddrTarget{Host: "fe80::43:ecff:fec9:1683", Port: 0, Err: nil}},
{Addr: "[fe80::43:ecff:fec9:1683]:5705", Target: parseAddrTarget{Host: "fe80::43:ecff:fec9:1683", Port: 5705, Err: nil}},
{Addr: "fe80::43:ecff:fec9:1683", Target: parseAddrTarget{Host: "", Port: 0, Err: &net.AddrError{Err: "too many colons in address", Addr: "fe80::43:ecff:fec9:1683"}}},
{Addr: "[fe80::43:ecff:fec9:1683", Target: parseAddrTarget{Host: "", Port: 0, Err: &net.AddrError{Err: "missing ']' in address", Addr: "[fe80::43:ecff:fec9:1683"}}},
{Addr: "fe80::43:ecff:fec9:1683]:5678", Target: parseAddrTarget{Host: "", Port: 0, Err: &net.AddrError{Err: "too many colons in address", Addr: "fe80::43:ecff:fec9:1683]:5678"}}},
}
for _, tc := range testCases {
t.Run(fmt.Sprintf("addr: %s", tc.Addr), func(t *testing.T) {
Expand Down

0 comments on commit d2af6e8

Please sign in to comment.