From 658a9d0f471b903035869ffadece5806768ab690 Mon Sep 17 00:00:00 2001 From: Doug Davis Date: Thu, 11 Sep 2014 16:32:09 -0700 Subject: [PATCH] Fix parsing of proto/port Signed-off-by: Doug Davis --- nat/nat.go | 28 ++++++++++++++++------------ nat/nat_test.go | 12 ++++++++++++ 2 files changed, 28 insertions(+), 12 deletions(-) diff --git a/nat/nat.go b/nat/nat.go index 3624eef729..b0177289ce 100644 --- a/nat/nat.go +++ b/nat/nat.go @@ -61,21 +61,25 @@ func (p Port) Int() int { return i } -// Splits a port in the format of port/proto +// Splits a port in the format of proto/port func SplitProtoPort(rawPort string) (string, string) { - parts := strings.Split(rawPort, "/") - l := len(parts) - if l == 0 { - return "", "" - } - if l == 1 { - if rawPort == "" { - return "", "" // ""/tcp is not valid, ever - } + var port string + var proto string - return "tcp", rawPort + parts := strings.Split(rawPort, "/") + + if len(parts) == 0 || parts[0] == "" { // we have "" or ""/ + port = "" + proto = "" + } else { // we have # or #/ or #/... + port = parts[0] + if len(parts) > 1 && parts[1] != "" { + proto = parts[1] // we have #/... + } else { + proto = "tcp" // we have # or #/ + } } - return parts[1], parts[0] + return proto, port } func validateProto(proto string) bool { diff --git a/nat/nat_test.go b/nat/nat_test.go index 80a6169c55..a8c2cb584e 100644 --- a/nat/nat_test.go +++ b/nat/nat_test.go @@ -84,6 +84,18 @@ func TestSplitProtoPort(t *testing.T) { if proto != "tcp" || port != "1234" { t.Fatal("tcp is not the default protocol for portspec '1234'") } + + proto, port = SplitProtoPort("1234/") + + if proto != "tcp" || port != "1234" { + t.Fatal("parsing '1234/' yielded:" + port + "/" + proto) + } + + proto, port = SplitProtoPort("/tcp") + + if proto != "" || port != "" { + t.Fatal("parsing '/tcp' yielded:" + port + "/" + proto) + } } func TestParsePortSpecs(t *testing.T) {