From 0fccef237d5440b4859c3f5656dc268b8007c16f Mon Sep 17 00:00:00 2001 From: Alex Dadgar Date: Wed, 25 Oct 2017 15:09:43 -0700 Subject: [PATCH] Initialize freeport lazily to avoid runtime issues This PR makes freeport initialize lazily rather than using an init method. --- lib/freeport/freeport.go | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/lib/freeport/freeport.go b/lib/freeport/freeport.go index c09ff4cd61..882998314f 100644 --- a/lib/freeport/freeport.go +++ b/lib/freeport/freeport.go @@ -40,11 +40,16 @@ var ( // mu guards nextPort 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 int ) -func init() { +// initialize is used to initialize freeport. +func initialize() { if lowPort+maxBlocks*blockSize > 65535 { 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") } + // Reserve a port block + once.Do(initialize) + for len(ports) < n { port++