是否可以检查WebSocket 403响应

Is it possible to check for WebSocket 403 responses?

本文关键字:响应 WebSocket 检查 是否      更新时间:2023-09-26

是否可以通过编程方式检查WebSocket连接是否失败并获得403响应?例如,使用以下服务器代码:

package main
import (
    "errors"
    "io"
    "log"
    "net/http"
    "golang.org/x/net/websocket"
)
func main() {
    handler := websocket.Handler(func(ws *websocket.Conn) {
        io.Copy(ws, ws)
    })
    handshake := func(conf *websocket.Config, req *http.Request) error {
        if req.URL.Path == "/sekret" {
            return nil
        }
        return errors.New("Oops!")
    }
    server := &websocket.Server{
        Handshake: handshake,
        Handler:   handler,
    }
    log.Fatal(http.ListenAndServe(":8080", server))
}

和下面触发403响应的JS连接示例:

var ws = new WebSocket("ws://localhost:8080/something"); 
ws.onerror = console.log;

错误响应是类型为"error"Event。另一方面,以下JS代码触发net::ERR_CONNECTION_REFUSED(至少在Chrome上):

var ws = new WebSocket("ws://localhost:8081/something"); 
ws.onerror = console.log;

错误事件对象看起来几乎完全相同。是否有办法从客户端区分WebSocket连接中的错误类型?(我特别寻找403响应,所以我可以提醒用户采取特殊行动。)

显然这是故意的:

我的理解是,出于安全原因,WebSocket错误状态是相当有限的,以限制恶意JS探测内部网络的能力。