mirror of
https://github.com/kataras/iris.git
synced 2025-12-20 03:17:04 +00:00
Implement the websocket adaptor, a version of kataras/go-websocket, and refactor all of the previous websocket examples.
https://github.com/kataras/go-websocket/issues/27 Former-commit-id: 0b7e52e0a61150a8bba973ef653986d8b3ddd26b
This commit is contained in:
62
adaptors/websocket/websocket.go
Normal file
62
adaptors/websocket/websocket.go
Normal file
@@ -0,0 +1,62 @@
|
||||
// Package websocket provides an easy way to setup server and client side rich websocket experience for Iris
|
||||
package websocket
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"gopkg.in/kataras/iris.v6"
|
||||
)
|
||||
|
||||
// New returns a new websocket server policy adaptor.
|
||||
func New(cfg Config) Server {
|
||||
return &server{
|
||||
config: cfg.Validate(),
|
||||
rooms: make(map[string][]string, 0),
|
||||
onConnectionListeners: make([]ConnectionFunc, 0),
|
||||
}
|
||||
}
|
||||
|
||||
func fixPath(s string) string {
|
||||
if s == "" {
|
||||
return ""
|
||||
}
|
||||
|
||||
if s[0] != '/' {
|
||||
s = "/" + s
|
||||
}
|
||||
|
||||
s = strings.Replace(s, "//", "/", -1)
|
||||
return s
|
||||
}
|
||||
|
||||
// Adapt implements the iris' adaptor, it adapts the websocket server to an Iris station.
|
||||
func (s *server) Adapt(frame *iris.Policies) {
|
||||
// bind the server's Handler to Iris at Boot state
|
||||
evt := iris.EventPolicy{
|
||||
Boot: func(f *iris.Framework) {
|
||||
wsPath := fixPath(s.config.Endpoint)
|
||||
if wsPath == "" {
|
||||
f.Log(iris.DevMode, "websocket's configuration field 'Endpoint' cannot be empty, websocket server stops")
|
||||
return
|
||||
}
|
||||
|
||||
wsClientSidePath := fixPath(s.config.ClientSourcePath)
|
||||
if wsClientSidePath == "" {
|
||||
f.Log(iris.DevMode, "websocket's configuration field 'ClientSourcePath' cannot be empty, websocket server stops")
|
||||
return
|
||||
}
|
||||
|
||||
// set the routing for client-side source (javascript) (optional)
|
||||
clientSideLookupName := "iris-websocket-client-side"
|
||||
wsHandler := s.Handler()
|
||||
f.Get(wsPath, wsHandler)
|
||||
// check if client side doesn't already exists
|
||||
if f.Routes().Lookup(clientSideLookupName) == nil {
|
||||
// serve the client side on domain:port/iris-ws.js
|
||||
f.StaticContent(wsClientSidePath, "application/javascript", ClientSource).ChangeName(clientSideLookupName)
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
evt.Adapt(frame)
|
||||
}
|
||||
Reference in New Issue
Block a user