Reputation: 5375
I have a simple go web server which serves on port localhost:8080 an public folder containing both an html file as well as a client script with websocket logic.
in my main.go file
listener, err := net.listen("tcp", "localhost:8080")
if err != nil {
log.Fatal(err)
}
//full code in gist https://gist.github.com/Kielan/98706aaf5dc0be9d6fbe
then in my client script
try {
var sock = new WebSocket("ws://127.0.0.1:8080");
console.log("Websocket - status: " + sock.readyState);
sock.onopen = function(message) {
console.log("CONNECTION opened..." + this.readyState);
//onmessage, onerr, onclose, ect...
}
I get the error in chrome
WebSocket connection to 'ws://127.0.0.1:8080/' failed: Error during WebSocket handshake: Unexpected response code: 200
and Firefox
Firefox can't establish a connection to the server at ws://127.0.0.1:8080/.
I found this article referring to node.js indicating to add /websocket to my client websocket string, though it did not solve the problem and resulted in a 404
I thought response code 200 is good, do I need to convert the request to a websocket somehow and maybe it is defaulting to http? If so how can I do this?
Upvotes: 0
Views: 3936
Reputation: 4699
Like JimB pointed out, you are not handling http nor websocket connections yet.
You can do websocket handling with the package github.com/gorilla/websocket
This is how a simple setup could look like:
package main
import (
"log"
"net/http"
"github.com/gorilla/websocket"
)
// wsHandler implements the Handler Interface
type wsHandler struct{}
func main() {
router := http.NewServeMux()
router.Handle("/", http.FileServer(http.Dir("./webroot"))) //handles static html / css etc. under ./webroot
router.Handle("/ws", wsHandler{}) //handels websocket connections
//serving
log.Fatal(http.ListenAndServe("localhost:8080", router))
}
func (wsh wsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// upgrader is needed to upgrade the HTTP Connection to a websocket Connection
upgrader := &websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
//Upgrading HTTP Connection to websocket connection
wsConn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Printf("error upgrading %s", err)
return
}
//handle your websockets with wsConn
}
In your Javascript you then need var sock = new WebSocket("ws://localhost/ws:8080");
obviously.
Upvotes: 1