40 lines
719 B
Go
40 lines
719 B
Go
package netutil
|
|
|
|
import (
|
|
"net"
|
|
"strconv"
|
|
)
|
|
|
|
// EnsurePort makes sure the address in [host] contains a port.
|
|
func EnsurePort(host, port string) string {
|
|
if _, _, err := net.SplitHostPort(host); err == nil {
|
|
return host
|
|
}
|
|
return net.JoinHostPort(host, port)
|
|
}
|
|
|
|
// Host returns the bare host (without port).
|
|
func Host(name string) string {
|
|
host, _, err := net.SplitHostPort(name)
|
|
if err == nil {
|
|
return host
|
|
}
|
|
return name
|
|
}
|
|
|
|
// Port returns the port number.
|
|
func Port(name string) int {
|
|
_, port, err := net.SplitHostPort(name)
|
|
if err != nil {
|
|
return 0
|
|
}
|
|
|
|
if i, err := net.LookupPort("tcp", port); err == nil {
|
|
return i
|
|
}
|
|
|
|
// TODO: name resolution for ports?
|
|
i, _ := strconv.Atoi(port)
|
|
return i
|
|
}
|