To use a random available port in Golang, you can use :0. I believe the port 0 would works for another language as well as I tried in python.
1
2
$ python -m SimpleHTTPServer 0Serving HTTP on 0.0.0.0 port 43481 ...
According to lifewire, port 0 is a non-ephemeral port that works as a wildcard that tells the system to find any available ports particularly in the Unix OS.
packagemainimport("log""net""net/http")funccreateListener()(lnet.Listener,closefunc()){l,err:=net.Listen("tcp",":0")iferr!=nil{panic(err)}returnl,func(){_=l.Close()}}funcmain(){l,close:=createListener()deferclose()http.Handle("/",http.HandlerFunc(func(rwhttp.ResponseWriter,r*http.Request){// handle like normal}))log.Println("listening at",l.Addr().(*net.TCPAddr).Port)http.Serve(l,nil)}
Execute it:
1
2
$ go run main.go
2022/01/04 17:40:16 listening at 33845
Thank you for reading!
···
Love This Content?
Any kind of supports is greatly appreciated! Kindly support me via Bitcoin, Ko-fi, Trakteer, or just continue to read another content. You can write a response via Webmention and let me know the URL via Telegraph.