更新:使用 js websockets 发送原点 header

Update: Send the origin header with js websockets

我一直在玩 Go 中的 gorilla-websocket,当我实现基本的 echo 示例时,我在部署服务器后记录了一个错误,

Origin is not found Websocket version != 13

我找到了一种方法来绕过这个问题,方法是使检查原点的函数始终 return true

var wsUpgrader = websocket.Upgrader{
    ReadBufferSize:  1024,
    WriteBufferSize: 1024,
    CheckOrigin: func(r *http.Request) bool {
        return true
    },
}

但感觉不对。因此,我正在寻找解决该问题的方法。

更新:再看一遍这个问题后,我似乎真的想将原点 header 添加到客户端实现,即 javascript websocket 实现

@benjic 我通过 javascript html5 应用程序连接到 websocket,该应用程序未托管在同一服务器上,但由我通过 chrome

在本地 运行

那我该怎么做呢。

通读 Gorilla 库的 Gorilla WebSocket Documentation indicates that when a nil value is provided for the CheckOrigin field of an Upgrader type a safe default is used. The default checks the Origin field of the incoming request with the Host header value to confirm they are equal before allowing the request. The documentation indicates that browsers do not enforce cross origin validity and it is the responsibility of the server application to enforce. You can see exactly how this is done in the source code

文档和来源表明 Upgrade function in the websocket package that acts as a factory for your example code above. The factory function 采用自定义缓冲区大小并将 CheckOrigin 覆盖为始终 return true。您可以在 HttpHandler 中使用此工厂函数来升级您的连接,而不是创建自定义 Upgrader

func webSocketHandler(w http.ResponseWriter, r *http.Request) {
    conn, err := websocket.Upgrade(w, r, nil, 1024, 1024)
    defer conn.Close()

    if err != nil {
        http.Error(w, err, http.StatusInternalServerError)
        return
    }

    conn.WriteMessage(websocket.TextMessage, []byte("Hello, world!"))
}

将您的 html 部署到服务器,例如 nginx 或仅使用节点启动。然后它将在浏览器中获取主机名和端口。

然后在创建时允许该地址 Upgrader ,例如:

var origins = []string{ "http://127.0.0.1:18081", "http://localhost:18081", "http://example.com"}
var _ = websocket.Upgrader{
    // Resolve cross-domain problems
    CheckOrigin: func(r *http.Request) bool {
        var origin = r.Header.Get("origin")
        for _, allowOrigin := range origins {
            if origin == allowOrigin {
                return true
            }
        }
        return false
    }}