DEV Community

Clavin June
Clavin June

Posted on • Originally published at clavinjune.dev on

1 1

Listening to Random Available Port in Go

Photo by @mbaumi on Unsplash

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.

$ python -m SimpleHTTPServer 0
Serving HTTP on 0.0.0.0 port 43481 ...
Enter fullscreen mode Exit fullscreen mode

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.

The Go Code

package main

import (
    "log"
    "net"
    "net/http"
)

func createListener() (l net.Listener, close func()) {
    l, err := net.Listen("tcp", ":0")
    if err != nil {
        panic(err)
    }

    return l, func() {
        _ = l.Close()
    }
}

func main() {
    l, close := createListener()
    defer close()

    http.Handle("/", http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
        // handle like normal
    }))

    log.Println("listening at", l.Addr().(*net.TCPAddr).Port)
    http.Serve(l, nil)
}

Enter fullscreen mode Exit fullscreen mode

Execute it:

$ go run main.go 
2022/01/04 17:40:16 listening at 33845
Enter fullscreen mode Exit fullscreen mode

Thank you for reading!

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay