-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfreeport_stack.go
More file actions
48 lines (42 loc) · 1.11 KB
/
freeport_stack.go
File metadata and controls
48 lines (42 loc) · 1.11 KB
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
package netutils
import "github.com/phayes/freeport"
// FreePortStack stack allows you to locally store a list of autogenerated ports
// it is stateful to make sure ports aren't reused
type FreePortStack struct {
ports []int
}
// NewFreeportStack is a helper method to initialize a freeport stack
func NewFreeportStack() FreePortStack {
return FreePortStack{}
}
func (s *FreePortStack) containsPort(port int) bool {
for _, testPort := range s.ports {
if testPort == port {
return true
}
}
return false
}
// GetFreePort gets a free port that has not already been used in the stack
// returns errors if they exist
func (s *FreePortStack) GetFreePort() (port int, err error) {
port, err = freeport.GetFreePort()
if err != nil {
return 0, err
}
// TODO we need to add a loop iterator here
if s.containsPort(port) {
return s.GetFreePort()
}
s.ports = append(s.ports, port)
return port, err
}
// GetPort gets a free port that has not already been used in the stack
// panics on error
func (s *FreePortStack) GetPort() (port int) {
port, err := s.GetFreePort()
if err != nil {
panic(err)
}
return port
}