Golang Serve Random Available Port Link to heading

In Go, you can specify the address of an HTTP server as :0. This will default to an Available port defined by the system.

http.ListenAndServe(":0", handler)

If you need to keep track of which port you can use a TCP Listener from the net package

func serveRandomPort(handler http.Handler) int {
	listener, err := net.Listen("tcp", ":0")
	if err != nil {
		log.Fatal(err)
	}
	go http.Serve(listener, handler)

	port := listener.Addr().(*net.TCPAddr).Port
    return port
}