-
Notifications
You must be signed in to change notification settings - Fork 251
/
Copy pathports.go
80 lines (66 loc) · 1.75 KB
/
ports.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package server
import (
"fmt"
"time"
"go.uber.org/zap"
)
// portManager is responsible for maintaining segregated access to the port field
type portManger struct {
logger *zap.Logger
port int
afterPortChanged func(port int)
}
// newPortManager returns a newly initialised portManager
func newPortManager(logger *zap.Logger, afterPortChanged func(int)) portManger {
pm := portManger{
logger: logger.Named("portManger"),
afterPortChanged: afterPortChanged,
}
return pm
}
// SetPort sets portManger.port field to the given port value
// next triggers any given portManger.afterPortChanged function
func (p *portManger) SetPort(port int) error {
l := p.logger.Named("SetPort")
l.Debug("fired", zap.Int("port", port))
if port == 0 {
errMsg := "port can not be `0`, use ResetPort() instead"
l.Error(errMsg)
return fmt.Errorf(errMsg)
}
p.port = port
if p.afterPortChanged != nil {
l.Debug("p.afterPortChanged != nil")
p.afterPortChanged(port)
}
return nil
}
// ResetPort resets portManger.port to 0
func (p *portManger) ResetPort() {
l := p.logger.Named("ResetPort")
l.Debug("fired")
p.port = 0
}
// GetPort gets the current value of portManager.port without any concern for the state of its value
// and therefore does not wait if portManager.port is 0
func (p *portManger) GetPort() int {
l := p.logger.Named("GetPort")
l.Debug("fired")
return p.port
}
// MustGetPort only returns portManager.port if portManager.port is not 0.
func (p *portManger) MustGetPort() int {
l := p.logger.Named("MustGetPort")
l.Debug("fired")
for {
if p.port != 0 {
port := p.port
if port == 0 {
panic("port is zero, port has reset")
}
return port
}
l.Debug("port is zero")
time.Sleep(20 * time.Millisecond)
}
}