forked from vladimirvivien/gomes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.go
50 lines (44 loc) · 893 Bytes
/
util.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package gomes
import (
"net"
"net/url"
"strconv"
"strings"
)
type address string
func (addr address) AsFullHttpURL(path string) (*url.URL, error) {
return &url.URL{
Scheme: HTTP_SCHEME,
Host: string(addr),
Path: path,
}, nil
}
func (addr address) AsHttpURL() (*url.URL, error) {
return &url.URL{
Scheme: HTTP_SCHEME,
Host: string(addr),
}, nil
}
func localIP4String() string {
addrs, _ := net.InterfaceAddrs()
for _, addr := range addrs {
switch addr.(type) {
case *net.IPNet:
ip := addr.(*net.IPNet)
if !ip.IP.IsLoopback() && ip.IP.To4() != nil {
return ip.String()[:strings.LastIndex(ip.String(), "/")]
}
}
}
return ""
}
func nextTcpPort() int {
l, err := net.Listen("tcp4", ":0")
defer l.Close()
addr := l.Addr().String()
port, err := strconv.Atoi(addr[strings.LastIndex(addr, ":")+1:])
if err != nil {
return 0
}
return port
}