Websocket closed very quickly

I’m trying this websocket example:

package main

import (
	"fmt"
	"log"
	"net/http"

	"golang.org/x/net/websocket"
)

func Echo(ws *websocket.Conn) {
	var err error

	for {
		var reply string

		if err = websocket.Message.Receive(ws, &reply); err != nil {
			fmt.Println("Can't receive")
			break
		}

		fmt.Println("Received back from client: " + reply)

		msg := "Received:  " + reply
		fmt.Println("Sending to client: " + msg)

		if err = websocket.Message.Send(ws, msg); err != nil {
			fmt.Println("Can't send")
			break
		}
	}
}

func main() {
	http.Handle("/", websocket.Handler(Echo))

	if err := http.ListenAndServe(":1234", nil); err != nil {
		log.Fatal("ListenAndServe:", err)
	}
}

With this client:

<html>
<head></head>
<body>
    <script type="text/javascript">
        var sock = null;
        var wsuri = "ws://localhost:1234";

        window.onload = function() {

            console.log("onload");

            sock = new WebSocket(wsuri);

            sock.onopen = function() {
                console.log("connected to " + wsuri);
            }

            sock.onclose = function(e) {
                console.log("connection closed (" + e.code + ")");
            }

            sock.onmessage = function(e) {
                console.log("message received: " + e.data);
            }
        };

        function send() {
            var msg = document.getElementById('message').value;
            sock.send(msg);
        };
    </script>
    <h1>WebSocket Echo Test</h1>
    <form>
        <p>
            Message: <input id="message" type="text" value="Hello, world!">
        </p>
    </form>
    <button onclick="send();">Send Message</button>
</body>
</html>

But getting the below error:
enter image description here

the log says that the connection fails.

have you checked the Echo function is called?

Not directly related but the library’s documentation suggests to use something else:

This package currently lacks some features found in alternative and more actively maintained WebSocket packages:

websocket package - github.com/gorilla/websocket - Go Packages
websocket package - nhooyr.io/websocket - Go Packages

Tried nhooyr.io/websocket with the below code:

package main

import (
	"context"
	"fmt"
	"log"
	"net/http"
	"time"

	"nhooyr.io/websocket"
	"nhooyr.io/websocket/wsjson"
)

func main() {
	http.Handle("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		setupCORS(&w, r)
		c, err := websocket.Accept(w, r, nil)
		if err != nil {
			fmt.Println(err)
		}
		defer c.Close(websocket.StatusInternalError, "the sky is falling")

		ctx, cancel := context.WithTimeout(r.Context(), time.Second*10)
		defer cancel()

		var v interface{}
		err = wsjson.Read(ctx, c, &v)
		if err != nil {
			fmt.Println(err)
		}

		log.Printf("received: %v", v)

		c.Close(websocket.StatusNormalClosure, "")
	}))

	if err := http.ListenAndServe(":1234", nil); err != nil {
		log.Fatal("ListenAndServe:", err)
	}
}

func setupCORS(w *http.ResponseWriter, req *http.Request) {
	(*w).Header().Set("Access-Control-Allow-Origin", "*")
	(*w).Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
	(*w).Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
}

But got the same error in the browser, with the below in the console:

failed to accept WebSocket connection: request Origin "null" is not authorized for Host "localhost:1234"
2022/06/11 17:50:38 http: panic serving [::1]:55059: runtime error: invalid memory address or nil pointer dereference
goroutine 19 [running]:
net/http.(*conn).serve.func1()
        D:/Development/go/src/net/http/server.go:1825 +0xbf
panic({0xa17580, 0xc35d00})
        D:/Development/go/src/runtime/panic.go:844 +0x258
nhooyr.io/websocket.(*Conn).writeClose(0x0, 0x3f3, {0xa549a5, 0x12})
        D:/Development/gopath/pkg/mod/nhooyr.io/websocket@v1.8.7/close_notjs.go:54 +0x51
nhooyr.io/websocket.(*Conn).closeHandshake(0xc000024140?, 0xaca8b0?, {0xa549a5?, 0xc00005a0d0?})
        D:/Development/gopath/pkg/mod/nhooyr.io/websocket@v1.8.7/close_notjs.go:37 +0x7a
nhooyr.io/websocket.(*Conn).Close(0xc00005a0c0?, 0x1?, {0xa549a5?, 0xc0000880c0?})
        D:/Development/gopath/pkg/mod/nhooyr.io/websocket@v1.8.7/close_notjs.go:31 +0x1e
panic({0xa17580, 0xc35d00})
        D:/Development/go/src/runtime/panic.go:838 +0x207
nhooyr.io/websocket.(*Conn).reader(0x0, {0xacb920, 0xc00005a0c0})
        D:/Development/gopath/pkg/mod/nhooyr.io/websocket@v1.8.7/read.go:303 +0xa4
nhooyr.io/websocket.(*Conn).Reader(...)
        D:/Development/gopath/pkg/mod/nhooyr.io/websocket@v1.8.7/read.go:30
nhooyr.io/websocket/wsjson.read({0xacb920?, 0xc00005a0c0?}, 0xc0000919d0?, {0xa03340, 0xc00004c170})
        D:/Development/gopath/pkg/mod/nhooyr.io/websocket@v1.8.7/wsjson/wsjson.go:23 +0xa5
nhooyr.io/websocket/wsjson.Read(...)
        D:/Development/gopath/pkg/mod/nhooyr.io/websocket@v1.8.7/wsjson/wsjson.go:17
main.main.func1({0xacb7c0, 0xc000070000}, 0xc00006a000)
        D:/Deployment/websocket/main.go:28 +0x1c5
net/http.HandlerFunc.ServeHTTP(0x266ab65a648?, {0xacb7c0?, 0xc000070000?}, 0x7cd0e5?)
        D:/Development/go/src/net/http/server.go:2084 +0x2f
net/http.(*ServeMux).ServeHTTP(0x0?, {0xacb7c0, 0xc000070000}, 0xc00006a000)
        D:/Development/go/src/net/http/server.go:2462 +0x149
net/http.serverHandler.ServeHTTP({0xc000020060?}, {0xacb7c0, 0xc000070000}, 0xc00006a000)
        D:/Development/go/src/net/http/server.go:2916 +0x43b
net/http.(*conn).serve(0xc00008caa0, {0xacb958, 0xc0000c2ed0})
        D:/Development/go/src/net/http/server.go:1966 +0x5d7
created by net/http.(*Server).Serve
        D:/Development/go/src/net/http/server.go:3071 +0x4db

I tested your server code with a Firefox websocket extension and it worked fine so check the code in your client

Which one you checked, the one using "golang.org/x/net/websocket" as in the original question, or the one using "nhooyr.io/websocket"

the first one, golang.org/x/net/websocket