mirror of https://github.com/docker/docs.git
drivers: extract splitPortProto to utility pkg
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 <andre.carvalho@corp.globo.com>
This commit is contained in:
parent
cfcdc63d52
commit
19de1c6ce6
|
@ -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
|
||||||
|
}
|
|
@ -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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in New Issue