1

I'm running a Go webserver using Gorilla/websocket for a real-time chess/chat application. As far as I know, I define the address and port in two locations, the Go http.ListenAndServer() method and the Javascript new Websocket(); function. This works great accross browsers on the same host machine, but it gets tricky when trying to extend the functionality over my internal network. So I use, for instance:

Go:

PORT := "0.0.0.0:8080"
// ...
http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
    h.serveWs(hub, w, r) // h is a chessboard Handler wrapper
})
//...
http.ListenAndServe(PORT, nil)

Javascript:

conn = new WebSocket("ws://0.0.0.0:8080/ws");

In my effort to get this working on different devices over the network I've tried using, instead of the 0.0.0.0 address, localhost or my hostname and my host's internal ip (e.g.) 10.232.44.20; With the latter, the internal ip hardcoded in, it works, but the other attempts don't. I thought that using 0.0.0.0 would accept all connections from within the network, which I gathered from this answer: What is the difference between 0.0.0.0, 127.0.0.1 and localhost?

How should I program ListenAndServe as well as new Websocket so that I can access the server within the internal network, without having to hardcode my internal ip address? Should I access that number programmatically from Js and Go? In the end, I want to be able to run this server on a variety of networks, without configuration, and have it just work. What am I missing?

Community
  • 1
  • 1
Nevermore
  • 7,141
  • 5
  • 42
  • 64

1 Answers1

3

If the web page and websocket endpoints are served by the same host, then create the websocket using the host used to fetch the web page:

conn = new WebSocket("ws://" + window.location.host + "/ws");

This will just work in all network configurations.

As far as the Go code is concerned, the easiest approach is to listen on all networks:

if err := http.ListenAndServe(":8080", nil); err != nil {
    // handle error
}
Charlie Tumahai
  • 113,709
  • 12
  • 249
  • 242