44 lines
1.2 KiB
Go
Raw Normal View History

2015-11-05 15:00:25 -08:00
package common
import (
"net"
"strings"
)
2017-07-19 15:02:04 -04:00
// Connect dials the given address and returns a net.Conn. The protoAddr argument should be prefixed with the protocol,
// eg. "tcp://127.0.0.1:8080" or "unix:///tmp/test.sock"
2015-11-05 15:00:25 -08:00
func Connect(protoAddr string) (net.Conn, error) {
2017-07-19 15:02:04 -04:00
proto, address := ProtocolAndAddress(protoAddr)
2015-11-05 15:00:25 -08:00
conn, err := net.Dial(proto, address)
return conn, err
}
2017-07-19 15:02:04 -04:00
// ProtocolAndAddress splits an address into the protocol and address components.
// For instance, "tcp://127.0.0.1:8080" will be split into "tcp" and "127.0.0.1:8080".
// If the address has no protocol prefix, the default is "tcp".
func ProtocolAndAddress(listenAddr string) (string, string) {
protocol, address := "tcp", listenAddr
parts := strings.SplitN(address, "://", 2)
if len(parts) == 2 {
protocol, address = parts[0], parts[1]
}
return protocol, address
}
2019-02-06 10:14:03 -05:00
// GetFreePort gets a free port from the operating system.
// Ripped from https://github.com/phayes/freeport.
// BSD-licensed.
func GetFreePort() (int, error) {
addr, err := net.ResolveTCPAddr("tcp", "localhost:0")
if err != nil {
return 0, err
}
l, err := net.ListenTCP("tcp", addr)
if err != nil {
return 0, err
}
defer l.Close()
return l.Addr().(*net.TCPAddr).Port, nil
}