1
0
mirror of https://github.com/kataras/iris.git synced 2025-12-18 10:27:06 +00:00

MVC improvements: add HandleWebsocket that now registers events automatically based on the struct's methods(!) and fix a bug when more than one value of the same type is registered to a static field of a controller

Former-commit-id: e369d1426ac1a6b58314930a18362670317da3c1
This commit is contained in:
Gerasimos (Makis) Maropoulos
2019-07-09 12:16:19 +03:00
parent 85666da682
commit 450f20902d
18 changed files with 383 additions and 183 deletions

View File

@@ -1,41 +1,45 @@
package main
import (
"fmt"
"sync/atomic"
"github.com/kataras/iris"
"github.com/kataras/iris/mvc"
"github.com/kataras/iris/websocket"
"github.com/kataras/neffos"
)
func main() {
app := iris.New()
app.Logger().SetLevel("debug")
// optionally enable debug messages to the neffos real-time framework
// and print them through the iris' logger.
neffos.EnableDebug(app.Logger())
// load templates.
app.RegisterView(iris.HTML("./views", ".html"))
// render the ./views/index.html.
app.Get("/", func(ctx iris.Context) {
ctx.View("index.html")
})
// render the ./browser/index.html.
app.HandleDir("/", "./browser")
mvc.Configure(app.Party("/websocket"), configureMVC)
// Or mvc.New(app.Party(...)).Configure(configureMVC)
websocketAPI := app.Party("/websocket")
m := mvc.New(websocketAPI)
m.Register(
&prefixedLogger{prefix: "DEV"},
)
m.HandleWebsocket(&websocketController{Namespace: "default", Age: 42, Otherstring: "other string"})
websocketServer := neffos.New(websocket.DefaultGorillaUpgrader, m)
websocketAPI.Get("/", websocket.Handler(websocketServer))
// http://localhost:8080
app.Run(iris.Addr(":8080"))
}
func configureMVC(m *mvc.Application) {
ws := websocket.New(websocket.Config{})
// http://localhost:8080/websocket/iris-ws.js
m.Router.Any("/iris-ws.js", websocket.ClientHandler())
// This will bind the result of ws.Upgrade which is a websocket.Connection
// to the controller(s) served by the `m.Handle`.
m.Register(ws.Upgrade)
m.Handle(new(websocketController))
}
var visits uint64
func increment() uint64 {
@@ -47,36 +51,74 @@ func decrement() uint64 {
}
type websocketController struct {
// Note that you could use an anonymous field as well, it doesn't matter, binder will find it.
//
// This is the current websocket connection, each client has its own instance of the *websocketController.
Conn websocket.Connection
*neffos.NSConn `stateless:"true"`
Namespace string
Age int
Otherstring string
Logger LoggerService
}
func (c *websocketController) onLeave(roomName string) {
// or
// func (c *websocketController) Namespace() string {
// return "default"
// }
func (c *websocketController) OnNamespaceDisconnect(msg neffos.Message) error {
c.Logger.Log("Disconnected")
// visits--
newCount := decrement()
// This will call the "visit" event on all clients, except the current one,
// This will call the "OnVisit" event on all clients, except the current one,
// (it can't because it's left but for any case use this type of design)
c.Conn.To(websocket.Broadcast).Emit("visit", newCount)
c.Conn.Server().Broadcast(nil, neffos.Message{
Namespace: msg.Namespace,
Event: "OnVisit",
Body: []byte(fmt.Sprintf("%d", newCount)),
})
return nil
}
func (c *websocketController) update() {
func (c *websocketController) OnNamespaceConnected(msg neffos.Message) error {
// println("Broadcast prefix is: " + c.BroadcastPrefix)
c.Logger.Log("Connected")
// visits++
newCount := increment()
// This will call the "visit" event on all clients, including the current
// This will call the "OnVisit" event on all clients, including the current
// with the 'newCount' variable.
//
// There are many ways that u can do it and faster, for example u can just send a new visitor
// and client can increment itself, but here we are just "showcasing" the websocket controller.
c.Conn.To(websocket.All).Emit("visit", newCount)
c.Conn.Server().Broadcast(c, neffos.Message{
Namespace: msg.Namespace,
Event: "OnVisit",
Body: []byte(fmt.Sprintf("%d", newCount)),
})
return nil
}
func (c *websocketController) Get( /* websocket.Connection could be lived here as well, it doesn't matter */ ) {
c.Conn.OnLeave(c.onLeave)
c.Conn.On("visit", c.update)
func (c *websocketController) OnChat(msg neffos.Message) error {
ctx := websocket.GetContext(c.Conn)
// call it after all event callbacks registration.
c.Conn.Wait()
ctx.Application().Logger().Infof("[IP: %s] [ID: %s] broadcast to other clients the message [%s]",
ctx.RemoteAddr(), c, string(msg.Body))
c.Conn.Server().Broadcast(c, msg)
return nil
}
type LoggerService interface {
Log(string)
}
type prefixedLogger struct {
prefix string
}
func (s *prefixedLogger) Log(msg string) {
fmt.Printf("%s: %s\n", s.prefix, msg)
}