gowebsocketgo-fiber

How do I set status code and reason in gofiber/websocket/v2


This is code in frontend I'm use 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
}

This is code in backend. I'm use go fiber and gofiber 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
        }
}))

I try to set custom return code and reason but seem not work because in

newSocket.onclose = (event) => {
      console.log(`Socket connection closed: ${event.reason}`);
      setSocket(null); // Set the socket to null after closing
    }

I get empty result in event.reason and event.code alway 1006

How do I set code and reason properly?

I'm use "github.com/gofiber/fiber/v2" "github.com/gofiber/websocket/v2"


Solution

  • Write a close message before calling 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
    }