duanchanguo7603 2015-10-24 21:05
浏览 61
已采纳

更新:使用js websockets发送原始标头

I've been playing around with gorilla-websocket in Go, and as I implemented the basic echo example, I logged an error after deploying the server,

Origin is not found Websocket version != 13

I found a way to bypass this by making the function that checks the origin always return true

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

But it doesn't feel right. Therefore, I am looking for a way to fix that issue.

Update: After having another look at the issue it seems like I'm actually looking to add the origin header to the client implementation which is the javascript websocket implementation

@benjic Im connecting to the websocket via a javascript html5 application that isn't hosted on the same server but is run locally by me via chrome

So how do I do that.

  • 写回答

1条回答 默认 最新

  • dongtuanzi1080 2015-10-25 02:59
    关注

    Reading through the 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 for the Gorilla library.

    The documentation and source indicate an Upgrade function in the websocket package that acts as a factory for your example code above. The factory function takes a custom buffer size and overrides the CheckOrigin to always return true. Instead of creating a custom Upgrader you can use this factory function in the HttpHandler to upgrade your connections.

    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!"))
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料