在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中文网其他相关文章!