/
port.go
55 lines (44 loc) · 1.07 KB
/
port.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
51
52
53
54
55
package deployment
import (
"net"
"strconv"
"github.com/docker/go-connections/nat"
)
type Port struct {
IP string `json:"ip"`
Type string `json:"type"`
HostPort string `json:"host_port"`
ContainerPort string `json:"container_port"`
}
type PortProtocol string
const (
TCP PortProtocol = "tcp"
)
func fromPortMapToPortList(pMap nat.PortMap) []Port {
bindings := make([]Port, 0)
for container, hostBindings := range pMap {
for _, hostB := range hostBindings {
bindings = append(bindings, Port{
IP: hostB.HostIP,
HostPort: hostB.HostPort,
Type: container.Proto(),
ContainerPort: container.Port(),
})
}
}
return bindings
}
// findFreePort returns a free port on the host machine
func findFreePort() (string, error) {
addr, err := net.ResolveTCPAddr(string(TCP), "localhost:0")
if err != nil {
return "", err
}
listener, err := net.ListenTCP(string(TCP), addr)
if err != nil {
return "", err
}
defer listener.Close()
port := listener.Addr().(*net.TCPAddr).Port
return strconv.Itoa(port), nil
}