Skip to content

Websocket closed quicklu #343

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
hajsf opened this issue Jun 11, 2022 · 1 comment
Closed

Websocket closed quicklu #343

hajsf opened this issue Jun 11, 2022 · 1 comment

Comments

@hajsf
Copy link

hajsf commented Jun 11, 2022

Tried the below:

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) {
		fmt.Println("call done")
		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")
}

With the below html file:

<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 got the below error:

PS D:\Deployment\websocket> go run main.go
call done
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
@lurenyang418
Copy link

@hajsf your code about CORS is invalid. See https://github.com/nhooyr/websocket/blob/master/accept.go#L190.
you can make it with code below

c, err := websocket.Accept(w, r, &websocket.AcceptOptions{
	OriginPatterns: []string{"*"},
})

FYI. #194

@nhooyr nhooyr closed this as completed Mar 5, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants