Finding a random free port in Golang
2 points by gwynforthewyn 3 months ago | 3 comments- gwynforthewyn 3 months agoSimple technique, but I use it enough that it felt useful to share.
- curious_curios 3 months agoI think there’s potential for a race condition between when you close the Listener and the http server spins up on the no longer reserved port that we’ve seen with lots of tests being run in parallel. You can return the listener, use t.Cleanup to close it and serve your web server on it.
- gwynforthewyn 3 months agoThe race condition is definitely there, but if you use t.Cleanup to close the listener then the listener does not stop listening on the port until the end of the test. If you try to bind an http server to the port during a test then your http server will stop and return the error "bind: address already in use".
I'd be interested to know how you're working around that, if you are able to share.
- gwynforthewyn 3 months ago
- curious_curios 3 months ago
- 3 months ago