mirror of
https://github.com/kataras/iris.git
synced 2025-01-23 18:51:03 +01:00
d0104defa8
relative: https://github.com/kataras/iris/issues/1283 and removing pongo2 from vendor: https://github.com/kataras/iris/issues/1284 Former-commit-id: 3ec57b349f99faca2b8e36d9f7252db0b6ea080d
59 lines
1.9 KiB
Go
59 lines
1.9 KiB
Go
package main
|
|
|
|
import (
|
|
"log"
|
|
|
|
"github.com/kataras/iris"
|
|
"github.com/kataras/iris/websocket"
|
|
)
|
|
|
|
const namespace = "default"
|
|
|
|
// if namespace is empty then simply websocket.Events{...} can be used instead.
|
|
var serverEvents = websocket.Namespaces{
|
|
namespace: websocket.Events{
|
|
websocket.OnNamespaceConnected: func(nsConn *websocket.NSConn, msg websocket.Message) error {
|
|
log.Printf("[%s] connected to namespace [%s] with IP [%s]",
|
|
nsConn, msg.Namespace,
|
|
// with `GetContext` you can retrieve the Iris' `Context`, alternatively
|
|
// you can use the `nsConn.Conn.Socket().Request()` to get the raw `*http.Request`.
|
|
websocket.GetContext(nsConn.Conn).RemoteAddr())
|
|
return nil
|
|
},
|
|
websocket.OnNamespaceDisconnect: func(nsConn *websocket.NSConn, msg websocket.Message) error {
|
|
log.Printf("[%s] disconnected from namespace [%s]", nsConn, msg.Namespace)
|
|
return nil
|
|
},
|
|
"chat": func(nsConn *websocket.NSConn, msg websocket.Message) error {
|
|
// room.String() returns -> NSConn.String() returns -> Conn.String() returns -> Conn.ID()
|
|
log.Printf("[%s] sent: %s", nsConn, string(msg.Body))
|
|
|
|
// Write message back to the client message owner with:
|
|
// nsConn.Emit("chat", msg)
|
|
// Write message to all except this client with:
|
|
nsConn.Conn.Server().Broadcast(nsConn, msg)
|
|
return nil
|
|
},
|
|
},
|
|
}
|
|
|
|
func main() {
|
|
app := iris.New()
|
|
websocketServer := websocket.New(
|
|
websocket.DefaultGorillaUpgrader, /* DefaultGobwasUpgrader can be used too. */
|
|
serverEvents)
|
|
|
|
// serves the endpoint of ws://localhost:8080/echo
|
|
app.Get("/echo", websocket.Handler(websocketServer))
|
|
|
|
// serves the browser-based websocket client.
|
|
app.Get("/", func(ctx iris.Context) {
|
|
ctx.ServeFile("./browser/index.html", false)
|
|
})
|
|
|
|
// serves the npm browser websocket client usage example.
|
|
app.HandleDir("/browserify", "./browserify")
|
|
|
|
app.Run(iris.Addr(":8080"), iris.WithoutServerError(iris.ErrServerClosed))
|
|
}
|