Initialize freeport lazily to avoid runtime issues
This PR makes freeport initialize lazily rather than using an init method.
This commit is contained in:
parent
a73ed8c79a
commit
b5f8a16ea3
|
@ -40,11 +40,16 @@ var (
|
||||||
// mu guards nextPort
|
// mu guards nextPort
|
||||||
mu sync.Mutex
|
mu sync.Mutex
|
||||||
|
|
||||||
|
// once is used to do the initialization on the first call to retrieve free
|
||||||
|
// ports
|
||||||
|
once sync.Once
|
||||||
|
|
||||||
// port is the last allocated port.
|
// port is the last allocated port.
|
||||||
port int
|
port int
|
||||||
)
|
)
|
||||||
|
|
||||||
func init() {
|
// initialize is used to initialize freeport.
|
||||||
|
func initialize() {
|
||||||
if lowPort+maxBlocks*blockSize > 65535 {
|
if lowPort+maxBlocks*blockSize > 65535 {
|
||||||
panic("freeport: block size too big or too many blocks requested")
|
panic("freeport: block size too big or too many blocks requested")
|
||||||
}
|
}
|
||||||
|
@ -108,6 +113,9 @@ func Free(n int) (ports []int, err error) {
|
||||||
return nil, fmt.Errorf("freeport: block size too small")
|
return nil, fmt.Errorf("freeport: block size too small")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Reserve a port block
|
||||||
|
once.Do(initialize)
|
||||||
|
|
||||||
for len(ports) < n {
|
for len(ports) < n {
|
||||||
port++
|
port++
|
||||||
|
|
||||||
|
|
Loading…
Reference in New Issue