1 回答

TA贡献1712条经验 获得超3个赞
要拒绝 websocket 连接,请不要按照问题中的描述升级连接。浏览器 API 不提供有关连接被拒绝的原因的信息,因为该信息可能违反同源策略。
执行以下操作以将错误原因发送回客户端应用程序或用户:
升级连接。
发送带有错误原因的关闭消息。
关闭连接。
这是一个例子:
c, err := ctl.upgrader.Upgrade(ctx.Writer, ctx.Request, nil)
if err != nil {
// TODO: handle error
}
if contentId == "" || !exists {
c.WriteMessage(websocket.CloseMessage,
websocket.FormatCloseMessage(websocket.ClosePolicyViolation,
"bad content id or not exist"))
c.Close()
return
}
// Continue with non-error case here.
从 JS 中的关闭处理程序访问原因:
ws.onclose = function (evt) {
if (evt.code == 1008) { // 1008 is policy violation
console.log(evt.reason)
}
}
- 1 回答
- 0 关注
- 279 浏览
添加回答
举报