You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在gofiber/websocket/v2中设置自定义WebSocket关闭状态码与原因?

解决WebSocket自定义关闭状态码与原因不生效的问题

问题根源

直接调用c.Close()会跳过WebSocket的正常关闭握手流程,浏览器会判定连接为异常关闭,因此返回固定的1006状态码,且reason为空。要让前端拿到自定义的状态码和原因,必须先发送符合WebSocket规范的关闭控制帧,再关闭连接。

后端修改方案

使用gofiber/websocket的WriteControl方法发送关闭帧,确保完成握手后再关闭连接。状态码需遵循WebSocket规范:自定义码请使用3000-4999区间的值(1000-1015为标准保留码)。

修改后的后端代码:

import (
    "log"
    "time"
    "github.com/gofiber/websocket/v2"
)

app.Get("/:room/:id", websocket.New(func(c *websocket.Conn) {
    roomID := c.Params("room")
    room := rooms[roomID] // Get the room based on roomID

    if room == nil {
        // 自定义关闭状态码与原因
        closeCode := 4000
        closeReason := "指定房间不存在"

        // 发送WebSocket关闭控制帧,设置5秒超时确保帧发送完成
        err := c.WriteControl(
            websocket.CloseMessage,
            websocket.FormatCloseMessage(closeCode, closeReason),
            time.Now().Add(5*time.Second),
        )
        if err != nil {
            log.Printf("发送关闭帧失败: %v", err)
        }

        // 完成握手后关闭连接
        c.Close()
        return
    }
    // 其他业务逻辑...
}))

前端验证

前端代码无需修改,当后端正确发送关闭帧后,onclose事件中即可拿到自定义的code和reason:

newSocket.onclose = (event) => {
    console.log(`关闭状态码: ${event.code}, 原因: ${event.reason}`);
    setSocket(null);
}

内容的提问来源于stack exchange,提问作者Dewvie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 23:01:16