在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”
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 }
以上是如何在 go Fiber/websocket/v2 中設定狀態碼和原因的詳細內容。更多資訊請關注PHP中文網其他相關文章!