diff options
Diffstat (limited to 'util')
-rw-r--r-- | util/network.go | 25 | ||||
-rw-r--r-- | util/network_test.go | 14 |
2 files changed, 39 insertions, 0 deletions
diff --git a/util/network.go b/util/network.go new file mode 100644 index 00000000..4c393c37 --- /dev/null +++ b/util/network.go @@ -0,0 +1,25 @@ +package util + +import ( + "net" + "strings" + "syscall" + "errors" +) + +func CreateListener(address string) (net.Listener, error) { + dsn := strings.Split(address, "://") + if len(dsn) != 2 { + return nil, errors.New("Invalid DSN (tcp://:6001, unix://file.sock)") + } + + if dsn[0] != "unix" && dsn[0] != "tcp" { + return nil, errors.New("Invalid Protocol (tcp://:6001, unix://file.sock)") + } + + if dsn[0] == "unix" { + syscall.Unlink(dsn[1]) + } + + return net.Listen(dsn[0], dsn[1]) +}
\ No newline at end of file diff --git a/util/network_test.go b/util/network_test.go new file mode 100644 index 00000000..bdc7e0b7 --- /dev/null +++ b/util/network_test.go @@ -0,0 +1,14 @@ +package util + +import ( + "github.com/stretchr/testify/assert" + "testing" +) + +func TestCreateListener(t *testing.T) { + _, err := CreateListener("unexpected dsn"); + assert.Error(t, err, "Invalid DSN (tcp://:6001, unix://file.sock)") + + _, err = CreateListener("aaa://192.168.0.1"); + assert.Error(t, err, "Invalid Protocol (tcp://:6001, unix://file.sock)") +} |