gofiber / contrib

🧬 Repository for third party middlewares with dependencies
https://docs.gofiber.io/contrib/
MIT License
218 stars 115 forks source link

🤗 [Question]: Not sure how the socket.io requests are being handled #1102

Closed struckchure closed 4 months ago

struckchure commented 4 months ago

Question Description

I get this error whenever i try to connect

16/05/2024 07:31:01 | 404 | 110.75µs | 127.0.0.1 | GET | /socket.io/ | Cannot GET /socket.io/

it's expected, as I don't see anywhere the socket.io server was booted or anything.

Code Snippet (optional)

func NewWebsocketModule(app *fiber.App, deploymentHandler handlers.DeploymentHandlerInterface) {
    wsGroup := app.Group("/socket.io/")

    wsGroup.Use(func(c *fiber.Ctx) error {
        // IsWebSocketUpgrade returns true if the client
        // requested upgrade to the WebSocket protocol.
        if websocket.IsWebSocketUpgrade(c) {
            c.Locals("allowed", true)
            return c.Next()
        }
        return fiber.ErrUpgradeRequired
    })

    socketio.On(socketio.EventConnect, func(ep *socketio.EventPayload) {
        fmt.Printf("Connection event 1 - User: %s", ep.Kws.GetStringAttribute("user_id"))
    })
    socketio.On(types.DEPLOYMENT_LOG_STREAM_EVENT, deploymentHandler.StreamMachineDeployment)
    socketio.On(types.DEPLOYMENT_NOTIFICATION_EVENT, deploymentHandler.DeploymentNotification)
}

Checklist:

ReneWerner87 commented 4 months ago

@antoniodipinto can you help here ?

antoniodipinto commented 4 months ago

Any websocket requires a GET route to initiate, that's why @struckchure is getting a 404. And also there is no socketio.New established

func NewWebsocketModule(app *fiber.App, deploymentHandler handlers.DeploymentHandlerInterface) {
    wsGroup := app.Group("/socket.io/")

    wsGroup.Use(func(c *fiber.Ctx) error {
        // IsWebSocketUpgrade returns true if the client
        // requested upgrade to the WebSocket protocol.
        if websocket.IsWebSocketUpgrade(c) {
            c.Locals("allowed", true)
            return c.Next()
        }
        return fiber.ErrUpgradeRequired
    })

    socketio.On(socketio.EventConnect, func(ep *socketio.EventPayload) {
        fmt.Printf("Connection event 1 - User: %s", ep.Kws.GetStringAttribute("user_id"))
    })
    socketio.On(types.DEPLOYMENT_LOG_STREAM_EVENT, deploymentHandler.StreamMachineDeployment)
    socketio.On(types.DEPLOYMENT_NOTIFICATION_EVENT, deploymentHandler.DeploymentNotification)

    // =================== socketio.New added for GET request =====================
        wsGroup.Get("/init", socketio.New(func(kws *socketio.Websocket) {
             // handle the connection
             // more examples here https://github.com/gofiber/recipes/blob/master/socketio/main.go
    }))
}
struckchure commented 4 months ago

Thanks @antoniodipinto

To be sure, my connection URL should looks something like this ws://127.0.0.1:8000/socket.io/init? And also, would I be able to use the socket.io client with it?

I'm testing with postman with the ws client, it works, but it does not work with the socket-io client

antoniodipinto commented 4 months ago

The url is the right one, this library is not meant to be compatible with socketio client. Use a standard javascript implementation to use this. Something like this:

let socket = new WebSocket("ws://127.0.0.1:8000/socket.io/init");

socket.onopen = function(e) {
  alert("[open] Connection established");
  alert("Sending to server");
  socket.send("My name is John");
};

// here you will receive
socket.onmessage = function(event) {
  alert(`[message] Data received from server: ${event.data}`);
};

socket.onclose = function(event) {
  if (event.wasClean) {
    alert(`[close] Connection closed cleanly, code=${event.code} reason=${event.reason}`);
  } else {
    // e.g. server process killed or network down
    // event.code is usually 1006 in this case
    alert('[close] Connection died');
  }
};

socket.onerror = function(error) {
  alert(`[error]`);
};

Send data like this

socket.send({
// the payload you expect to receive in fiber
});

Remember, to fire an event you should use the Fire function from the decoded message object

struckchure commented 4 months ago

Thanks a lot @antoniodipinto

This was very helpful!