Fixed ports parsing

This commit is contained in:
Ivan Daniluk 2015-05-03 20:42:21 +03:00
parent fa535bf28d
commit 89c25ad79d
2 changed files with 83 additions and 0 deletions

View File

@ -3,6 +3,7 @@ package main
import ( import (
"errors" "errors"
"fmt" "fmt"
"net"
"path/filepath" "path/filepath"
"strings" "strings"
@ -36,6 +37,47 @@ func BaseCommand(cmdline []string) string {
// ParsePorts converts comma-separated ports into strings slice // ParsePorts converts comma-separated ports into strings slice
func ParsePorts(s string) ([]string, error) { func ParsePorts(s string) ([]string, error) {
var (
ports []string
err error
)
// Try simple mode, ports only ("1234-1235,80")
ports, err = parseRange(s)
if err == nil {
return ports, nil
}
var ErrParsePorts = fmt.Errorf("cannot parse ports argument")
// else, try host:ports notation ("localhost:1234-1235,remote:2000,2345")
fields := strings.FieldsFunc(s, func(r rune) bool { return r == ',' })
for _, field := range fields {
// split host:ports
var host, portsRange string
parts := strings.FieldsFunc(field, func(r rune) bool { return r == ':' })
if len(parts) == 1 {
host = "localhost"
} else if len(parts) == 2 {
host, portsRange = parts[0], parts[1]
} else {
return nil, ErrParsePorts
}
pp, err := parseRange(portsRange)
if err != nil {
return nil, ErrParsePorts
}
for _, p := range pp {
addr := net.JoinHostPort(host, p)
ports = append(ports, addr)
}
}
return ports, nil
}
func parseRange(s string) ([]string, error) {
portsInt, err := ranges.Parse(s) portsInt, err := ranges.Parse(s)
if err != nil { if err != nil {
return nil, err return nil, err

View File

@ -25,3 +25,44 @@ func TestUtils(t *testing.T) {
t.Fatalf("vars should contain 4 elements, but has %d", len(vars)) t.Fatalf("vars should contain 4 elements, but has %d", len(vars))
} }
} }
func TestPorts(t *testing.T) {
arg := "1234,1235"
ports, err := ParsePorts(arg)
if err != nil {
t.Fatal(err)
}
if len(ports) != 2 || ports[0] != "1234" {
t.Fatalf("ParsePorts returns wrong data: %v", ports)
}
arg = "1234-1237,2000"
ports, err = ParsePorts(arg)
if err != nil {
t.Fatal(err)
}
if len(ports) != 5 || ports[0] != "1234" || ports[4] != "2000" {
t.Fatalf("ParsePorts returns wrong data: %v", ports)
}
arg = "localhost:2000-2002,remote:1234-1235"
ports, err = ParsePorts(arg)
if err != nil {
t.Fatal(err)
}
if len(ports) != 5 || ports[0] != "localhost:2000" || ports[4] != "remote:1235" {
t.Fatalf("ParsePorts returns wrong data: %v", ports)
}
arg = "localhost:2000-2002,remote:1234-1235,some:weird:1234-123input"
_, err = ParsePorts(arg)
if err == nil {
t.Fatalf("err shouldn't be nil")
}
arg = "string,sdasd"
_, err = ParsePorts(arg)
if err == nil {
t.Fatalf("err shouldn't be nil")
}
}