Open URL on open port

hendry :

I'm assuming I can run a service on port 3000 like many other code samples I've seen on Github.

Now I am trying to improve my code so that it looks for an open port in case 3000 is in use:

for port := 3000; port <= 3005; port++ {
    fmt.Println(port)
    err := http.ListenAndServe(":"+strconv.Itoa(port), nil)
    if err == nil {
        fmt.Println("lk is serving", dirPath, "from http://0.0.0.0:", string(port))
        open.Start("http://0.0.0.0:" + string(port))
    }
}

However it blocks on the http.ListenAndServe line and doesn't open.Start my browser. I'm told I should use goroutines but I am still a bit bewildered how to use them in this context.

This is a "client" Web app so I do need it to invoke my browser.

Muffin Top :

Instead of calling ListenAndServe, create the Listener in the application and then call Serve. When creating the listener, request a free port by specifying the listener address as ":0":

ln, err := net.Listen("tcp", ":0")
if err != nil {
     // handle error
}

Once the listener is open, you can start the browser:

open.Start("http://" + ln.Addr().String())

and then start the server:

if err := http.Serve(ln, nil); err != nil {
   // handle error
}

There's no need to use a goroutine.

The code above uses addr.String() to format the listener's address. If you do need to get the port number for some reason, use a type assertion:

if a, ok := ln.Addr().(*net.TCPAddr); ok {
   fmt.Println("port", a.Port)
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related