golang Sec-WebSocket-Protocol问题记录

环境

golang 1.9

websocket包采用的是github.com/gorilla/websocket

在小程序H5页面与websocket联调的时候出现了如下错误,Sec-Websocket-Protocol参数应该是小程序中自己添加进去的,后端要做一些处理。

问题

image
Error during Websocket handshake: Sent non-empty 'Sec-Websocket-Protocol'header but no response was received

处理

一般而言,websocket出现这种问题只要获取请求头的Sec-Websocket-Protocol参数,随后将参数添加到response的请求头中即可。但我在尝试之后,问题并没有解决。

在部门大佬的指导下,去看了github.com/gorilla/websocket包的源代码,发现包里对于这个参数已经做了处理

    //源码
    // Subprotocols specifies the server's supported protocols in order of
    // preference. If this field is not nil, then the Upgrade method negotiates a
    // subprotocol by selecting the first match in this list with a protocol
    // requested by the client. If there's no match, then no protocol is
    // negotiated (the Sec-Websocket-Protocol header is not included in the
    // handshake response).
    Subprotocols []string
    
    
    func (u *Upgrader) selectSubprotocol(r *http.Request, responseHeader http.Header) string {
    if u.Subprotocols != nil {
        clientProtocols := Subprotocols(r)
        for _, serverProtocol := range u.Subprotocols {
            for _, clientProtocol := range clientProtocols {
                if clientProtocol == serverProtocol {
                    return clientProtocol
                }
            }
        }
    } else if responseHeader != nil {
        return responseHeader.Get("Sec-Websocket-Protocol")
    }
    return ""
}

所以我们只需要将获取的参数放进Subprotocols即可

var upgrade = websocket.Upgrader{
        // cross origin domain
        CheckOrigin: func(r *http.Request) bool {   //这个是解决跨域问题
            return true
        },
        Subprotocols:[]string{s.Ctx.Input.Header("Sec-WebSocket-Protocol")},  
        //将获取的参数放进这个数组,问题解决
    }

在引用第三方包的时候,遇到问题,多读源码

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 项目中的消息通知用到了websocket,感觉比http长连接分块发送好用,特此记录一下。WebSocket协议用...
    ywhu阅读 33,905评论 5赞 10
  • 理论知识可以参考网络信息怎么在网线中传播的 (转载自知乎)Android 网络(一) 概念 TCP/IP Sock...
    合肥黑阅读 19,171评论 1赞 8
  • WebSocket 机制 WebSocket 是 HTML5 一种新的协议。它实现了浏览器与服务器全双工通信,能更...
    勇敢的_心_阅读 2,426评论 0赞 4
  • 原文地址:http://www.ibm.com/developerworks/cn/java/j-lo-WebSo...
    敢梦敢当阅读 9,066评论 0赞 50
  • 考着考着,孩子就大了! 明天又是期末考了,孩子的第五个期末考!这场试考完,她的小学时光就只剩几个月了。人生的又一...
    雨梳草田阅读 182评论 0赞 0

友情链接更多精彩内容