freifunkmanager/websocket/server.go

54 lines
1.0 KiB
Go
Raw Normal View History

2017-05-08 19:13:29 +02:00
package websocket
import (
"net/http"
"golang.org/x/net/websocket"
httpLib "github.com/FreifunkBremen/freifunkmanager/lib/http"
"github.com/FreifunkBremen/freifunkmanager/lib/log"
"github.com/FreifunkBremen/freifunkmanager/runtime"
)
var nodes *runtime.Nodes
var clients map[string]*Client
func Start(nodeBind *runtime.Nodes) {
nodes = nodeBind
clients = make(map[string]*Client)
http.Handle("/websocket", websocket.Handler(func(ws *websocket.Conn) {
r := ws.Request()
ip := httpLib.GetRemoteIP(r)
2017-05-08 19:13:29 +02:00
defer func() {
ws.Close()
delete(clients, ip)
log.HTTP(r).Info("client disconnected")
2017-05-08 19:13:29 +02:00
}()
2017-05-08 19:13:29 +02:00
log.HTTP(r).Infof("new client")
2017-05-08 19:13:29 +02:00
client := NewClient(ip, ws)
clients[ip] = client
client.Listen()
2017-05-08 19:13:29 +02:00
}))
nodes.AddNotify(Notify)
}
func Notify(node *runtime.Node, real bool) {
msgType := MessageTypeUpdateNode
2017-05-08 19:13:29 +02:00
if real {
msgType = MessageTypeCurrentNode
2017-05-08 19:13:29 +02:00
}
for _, c := range clients {
c.Write(&Message{Type: msgType, Node: node})
2017-05-08 19:13:29 +02:00
}
}
func Close() {
log.Log.Infof("websocket stopped with %d clients", len(clients))
2017-05-08 19:13:29 +02:00
}