Skip to content

Instantly share code, notes, and snippets.

@xcsrz
Created January 2, 2016 07:12
Show Gist options
  • Save xcsrz/538e291d12be6ee9a8c7 to your computer and use it in GitHub Desktop.
Save xcsrz/538e291d12be6ee9a8c7 to your computer and use it in GitHub Desktop.
A golang web server on a randomly (os) chosen port.
package main
import (
"fmt"
"github.com/skratchdot/open-golang/open"
"net"
"net/http"
)
func main() {
http.HandleFunc("/", helloWorld)
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
panic(err)
}
fmt.Println("listening on", listener.Addr().String())
open.Run("http://" + listener.Addr().String())
panic(http.Serve(listener, nil))
}
func helloWorld(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("hello world"))
}
@brydavis
Copy link

brydavis commented Nov 5, 2018

You just answered my question, "how is the port being randomly assigned?", while debugging some other random project. Thanks!

@vzool
Copy link

vzool commented Sep 29, 2021

Thanks for sharing <3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment