在Go語言的Fiber/websocket/v2中,設置狀態代碼和原因是一個常見的需求。通過設置狀態代碼和原因,我們可以向客戶端提供有關請求處理情況的詳細信息。在本文中,我們將向您展示如何在Fiber/websocket/v2中輕松設置狀態代碼和原因。無論您是初學者還是有經驗的開發者,本文都將為您提供清晰的指導和實用的示例代碼。繼續閱讀,讓我們開始吧!
問題內容
這是前端代碼,我使用react js
const newSocket = new WebSocket(`ws://localhost:8080/${roomID}/${userID}`); setSocket(newSocket); // Set the socket in state newSocket.onclose = (event) => { console.log(`Socket connection closed: ${event.code}`); setSocket(null); // Set the socket to null after closing }
登錄后復制
這是后端的代碼。我使用 go Fiber 和 go Fiber websocket
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 { // Handle the case when the room does not exist log.Printf("Room %s does not exist", roomID) c.Close() return } }))
登錄后復制
我嘗試設置自定義返回代碼和原因,但似乎不起作用,因為
newSocket.onclose = (event) => { console.log(`Socket connection closed: ${event.reason}`); setSocket(null); // Set the socket to null after closing }
登錄后復制
我在 event.reason 和 event.code 中始終得到空結果 1006
如何正確設置代碼和推理?
我正在使用
“github.com/gocarbon/fibre/v2”
“github.com/go Fiber/websocket/v2”
解決方法
寫入一個在調用 Close()
之前關閉消息:
if room == nil { // Handle the case when the room does not exist log.Printf("Room %s does not exist", roomID) c.WriteControl(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, "room does not exist"), time.Now().Add(time.Second)) c.Close() return }
登錄后復制