From 19de1c6ce67e3dddc96f946b16085bd8ef491aa7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9=20Carvalho?= Date: Sat, 20 Aug 2016 15:42:59 -0300 Subject: [PATCH] drivers: extract splitPortProto to utility pkg MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This commit extracts the function to a common method where it will be able to be used accross multiple drivers. Signed-off-by: André Carvalho --- drivers/util/util.go | 23 +++++++++++++++++++++++ drivers/util/util_test.go | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 55 insertions(+) create mode 100644 drivers/util/util.go create mode 100644 drivers/util/util_test.go diff --git a/drivers/util/util.go b/drivers/util/util.go new file mode 100644 index 0000000000..c1239aea5a --- /dev/null +++ b/drivers/util/util.go @@ -0,0 +1,23 @@ +package util + +import ( + "fmt" + "strconv" + "strings" +) + +// SplitPortProto splits a string in the format port/protocol, defaulting +// protocol to "tcp" if not provided. +func SplitPortProto(raw string) (port int, protocol string, err error) { + parts := strings.Split(raw, "/") + if len(parts) == 1 { + protocol = "tcp" + } else { + protocol = parts[1] + } + port, err = strconv.Atoi(parts[0]) + if err != nil { + return 0, "", fmt.Errorf("invalid port number %s: %s", parts[0], err) + } + return port, protocol, nil +} diff --git a/drivers/util/util_test.go b/drivers/util/util_test.go new file mode 100644 index 0000000000..17ee988318 --- /dev/null +++ b/drivers/util/util_test.go @@ -0,0 +1,32 @@ +package util + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestSplitPortProtocol(t *testing.T) { + tests := []struct { + raw string + expectedPort int + expectedProto string + expectedErr bool + }{ + {"8080/tcp", 8080, "tcp", false}, + {"90/udp", 90, "udp", false}, + {"80", 80, "tcp", false}, + {"abc", 0, "", true}, + } + + for _, tc := range tests { + port, proto, err := SplitPortProto(tc.raw) + assert.Equal(t, tc.expectedPort, port) + assert.Equal(t, tc.expectedProto, proto) + if tc.expectedErr { + assert.Error(t, err) + } else { + assert.NoError(t, err) + } + } +}