-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathport.go
More file actions
45 lines (37 loc) · 743 Bytes
/
port.go
File metadata and controls
45 lines (37 loc) · 743 Bytes
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
package main
import (
"net"
"os"
)
func port() string {
var port string
PortEnvValue, isExist := os.LookupEnv("PORT")
if !isExist {
port = "9292"
} else {
port = PortEnvValue
}
return port
}
// GetFreePort asks the kernel for a free open port that is ready to use.
func GetFreePort() (int, error) {
addr, err := net.ResolveTCPAddr("tcp", ":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
}
// GetPort is deprecated, use GetFreePort instead
// Ask the kernel for a free open port that is ready to use
func GetPort() int {
port, err := GetFreePort()
if err != nil {
panic(err)
}
return port
}