Websockets
Iris has a trivial way of registering websocket events via a Go structure. The websocket controller is part of the MVC features.
Iris has its own iris/mvc/Application.HandleWebsocket(v interface{}) *neffos.Struct
to register controllers in existing Iris MVC applications(offering a fully featured dependency injection container for request values and static services).
Let's see a usage example, we want to bind the OnNamespaceConnected
, OnNamespaceDisconnect
built-in events and a custom "OnChat"
event with our controller's methods.
1. We create the controller by declaring a NSConn type field as stateless
and write the methods we need.
Iris is smart enough to catch the Namespace string
struct field to use it to register the controller's methods as events for that namespace, alternatively you can create a controller method of Namespace() string { return "default" }
or use the HandleWebsocket
's return value to .SetNamespace("default")
, it's up to you.
2. We inititalize our MVC application targets to a websocket endpoint, as we used to do with regular HTTP Controllers for HTTP routes.
3. We register our dependencies, if any.
4. We register one or more websocket controllers, each websocket controller maps to one namespace (just one is enough, as in most of the cases you don't need more, but that depends on your app's needs and requirements).
5. Next, we continue by mapping the mvc application as a connection handler to a websocket server (you may use more than one mvc applications per websocket server via neffos.JoinConnHandlers(mvcApp1, mvcApp2)
).
6. And the last step is to register that server to our endpoint through a normal .Get
method.
Last updated