diff --git a/nat/nat.go b/nat/nat.go index 2cec2e8..3805b2e 100644 --- a/nat/nat.go +++ b/nat/nat.go @@ -29,8 +29,16 @@ type PortSet map[Port]struct{} // 80/tcp type Port string -func NewPort(proto, port string) Port { - return Port(fmt.Sprintf("%s/%s", port, proto)) +func NewPort(proto, port string) (Port, error) { + // Check for parsing issues on "port" now so we can avoid having + // to check it later on. + + portInt, err := ParsePort(port) + if err != nil { + return "", err + } + + return Port(fmt.Sprintf("%d/%s", portInt, proto)), nil } func ParsePort(rawPort string) (int, error) { @@ -55,11 +63,15 @@ func (p Port) Port() string { } func (p Port) Int() int { - port, err := ParsePort(p.Port()) - if err != nil { - panic(err) + portStr := p.Port() + if len(portStr) == 0 { + return 0 } - return port + + // We don't need to check for an error because we're going to + // assume that any error would have been found, and reported, in NewPort() + port, _ := strconv.ParseUint(portStr, 10, 16) + return int(port) } // Splits a port in the format of proto/port @@ -152,7 +164,10 @@ func ParsePortSpecs(ports []string) (map[Port]struct{}, map[Port][]PortBinding, if len(hostPort) > 0 { hostPort = strconv.FormatUint(startHostPort+i, 10) } - port := NewPort(strings.ToLower(proto), containerPort) + port, err := NewPort(strings.ToLower(proto), containerPort) + if err != nil { + return nil, nil, err + } if _, exists := exposedPorts[port]; !exists { exposedPorts[port] = struct{}{} } diff --git a/nat/nat_test.go b/nat/nat_test.go index 5016831..0262a53 100644 --- a/nat/nat_test.go +++ b/nat/nat_test.go @@ -42,7 +42,11 @@ func TestParsePort(t *testing.T) { } func TestPort(t *testing.T) { - p := NewPort("tcp", "1234") + p, err := NewPort("tcp", "1234") + + if err != nil { + t.Fatalf("tcp, 1234 had a parsing issue: %v", err) + } if string(p) != "1234/tcp" { t.Fatal("tcp, 1234 did not result in the string 1234/tcp") @@ -59,6 +63,11 @@ func TestPort(t *testing.T) { if p.Int() != 1234 { t.Fatal("port int value was not 1234") } + + p, err = NewPort("tcp", "asd1234") + if err == nil { + t.Fatal("tcp, asd1234 was supposed to fail") + } } func TestSplitProtoPort(t *testing.T) {