1

For WebSockets support in Golang, many examples feature Fiber servers with endpoints like this:

    app.Use("/ws", func(c *fiber.Ctx) error {
        // IsWebSocketUpgrade returns true if the client
        // requested upgrade to the WebSocket protocol.
        if websocket.IsWebSocketUpgrade(c) {
            return c.Next()
        }
        return fiber.ErrUpgradeRequired
    })
    // Websocket handler
    app.Get("/ws/:id", websocket.New(func(ws *websocket.Conn) {
        handler.MediaStreamHandler(ws)
    }))

The app.Use endpoint here is well-documented: it initiates the WebSockets handshake and upgrades the connection protocol from HTTP to WebSockets.

Less clear is the app.Get endpoint. I understand the idiomatic point: it's where the receipt of real-time messaging over WebSockets takes place. But what is not clear is who calls app.Get, and how is the WebSockets interface persisted across invocations of app.Use and app.Get?

I am guessing state attached to the WebSockets interface is persisted in the Fiber app. But how is app.Get called? Is the WebSockets client expected to make a request to app.Get so the Fiber server is cued to begin receipt of real-time messaging?

Kode Charlie
  • 1,297
  • 16
  • 32

1 Answers1

1

app.Use registers a middleware, not a handler. So there really is no endpoint under /ws. The server as shown in the question would respond with status 404 for requests to /ws. The first argument simply limits the middleware to requests that have the given path prefix. From the docs:

Use registers a middleware route. Middleware matches requests beginning with the provided prefix. Providing a prefix is optional, it defaults to "/".

With this setup, clients are expected to initiate websocket connections with something like GET /ws/123 HTTP/1.1. Because this path starts with /ws, the websocket middleware runs before the handler registered with app.Get("/ws/:id", ...).

s.Next() in the middleware effectively calls the handler passed to app.Get.

Peter
  • 29,454
  • 5
  • 48
  • 60
  • so if I have a URL like `http://chat.acme.ai:80/ws/123`, and initiate an HTTP GET request to that URL, then the Fiber service should upgrade the socket to a WebSockets interface. But in that case, what does my client logic look like? IE, my client starts as an HTTP client making a GET call ... but how does that morph into a WebSockets client? – Kode Charlie Aug 29 '23 at 21:48