Skip to content

Instantly share code, notes, and snippets.

@arvenil
Created September 3, 2021 12:23
Show Gist options
  • Save arvenil/83add42f1b8b71925fa45af9401cc59d to your computer and use it in GitHub Desktop.
Save arvenil/83add42f1b8b71925fa45af9401cc59d to your computer and use it in GitHub Desktop.
port.go
// 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