MustGetFreePort returns a TCP port that is available to listen on, for the given (local) host. This works by binding a new TCP socket on port 0, which requests the OS to allocate a free port. There is no strict guarantee that the port will remain available after this function returns, but it should
()
| 24 | // |
| 25 | // Copied from github.com/temporalio/temporal/blob/main/common/testing/freeport/freeport.go. |
| 26 | func MustGetFreePort() int { |
| 27 | port, err := getFreePort("127.0.0.1") |
| 28 | if err != nil { |
| 29 | // try ipv6 |
| 30 | port, err = getFreePort("[::1]") |
| 31 | if err != nil { |
| 32 | panic(fmt.Errorf("failed assigning ephemeral port: %w", err)) |
| 33 | } |
| 34 | } |
| 35 | return port |
| 36 | } |
| 37 | |
| 38 | func getFreePort(host string) (int, error) { |
| 39 | l, err := net.Listen("tcp", host+":0") |