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 写uniapp时遇到的问题
  • ¥15 matlab有限元法求解梁带有若干弹簧质量系统的固有频率
  • ¥15 找一个网络防御专家,外包的
  • ¥100 能不能让两张不同的图片md5值一样,(有尝)
  • ¥15 informer代码训练自己的数据集,改参数怎么改
  • ¥15 请看一下,学校实验要求,我需要具体代码
  • ¥50 pc微信3.6.0.18不能登陆 有偿解决问题
  • ¥20 MATLAB绘制两隐函数曲面的交线
  • ¥15 求TYPCE母转母转接头24PIN线路板图
  • ¥100 国外网络搭建,有偿交流