Created
September 3, 2021 12:23
-
-
Save arvenil/83add42f1b8b71925fa45af9401cc59d to your computer and use it in GitHub Desktop.
port.go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Package port allows to obtain a free port that is ready to use. | |
package port | |
import ( | |
"net" | |
"emperror.dev/errors" | |
) | |
// New returns a free open port that is ready to use. | |
func New() (int, error) { | |
addr, err := net.ResolveTCPAddr("tcp", "127.0.0.1:0") | |
if err != nil { | |
return 0, errors.WithStack(err) | |
} | |
l, err := net.ListenTCP("tcp", addr) | |
if err != nil { | |
return 0, errors.WithStack(err) | |
} | |
defer l.Close() //nolint:errcheck | |
return l.Addr().(*net.TCPAddr).Port, nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment