Gorilla Websocket:WebSocket 握手期间出错:意外的响应代码:404

Gorilla Websocket: Error during WebSocket handshake: Unexpected response code: 404

我克隆了大猩猩 websocket 聊天示例并将其更新为使用多个房间。但是,我收到错误: Error during WebSocket handshake: Unexpected response code: 404 在 chrome 每当我尝试建立连接时。 github 上提供了我的源代码。它与原始示例非常相似,只是稍作改动。我不知道为什么它不起作用。

编辑: 问题出现在这行代码中:

for _, name := range []string{"arduino", "java", "go", "scala"} {
    room := newRoom("go")
    http.Handle("/chat/go", room)
    go room.run()
}

遍历切片导致 httphandle 函数出现问题。相反,我单独声明它们:

room := newRoom("go")
http.Handle("/chat/go", room)
go room.run()
...

有效。我该如何解决这个问题?

所以实际上从您的 index.html 文件,您连接到错误的 url

<!-- index.html -->
<script>
    var serviceLocation = "ws://0.0.0.0:8080/chat/";
.....

    function connectToChatserver() {
        room = $('#chatroom option:selected').val();
        wsocket = new WebSocket(serviceLocation + room);
        // it connect to /chat/<room>, it has slash after chat

这是你来自 main.go

的 url
    http.Handle("/chat"+name, room)

它会让 url 变成这样:http://localhost:8080/chatgo,而不是你想要的:http://localhost:8080/chat/go

Fyi,会报错是因为你没有正确处理channel,所以我发完1条消息后,就自动关闭了。不过这是另外一个话题了。

2020/08/04 06:42:10 running chat room java
2020/08/04 06:42:10 running chat room go
2020/08/04 06:42:10 running chat room arduino
2020/08/04 06:42:10 running chat room scala
2020/08/04 06:42:15 new client in room arduino
2020/08/04 06:42:15 client leaving room arduino
2020/08/04 06:42:15 client leaving room arduino
panic: close of closed channel

goroutine 6 [running]:
main.(*Room).run(0xc00007ac90)
        /home/fahim/Projects/Golang/go-chat/room.go:70 +0x3b5
created by main.main
        /home/fahim/Projects/Golang/go-chat/main.go:17 +0x2bd
exit status 2