-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsocket.go
61 lines (49 loc) · 1.28 KB
/
socket.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package catTrackslib
import (
"encoding/json"
"log"
"github.com/olahol/melody"
"github.com/paulmach/orb/geojson"
)
type websocketAction string
var websocketActionPopulate websocketAction = "populate"
type broadcats struct {
Action websocketAction `json:"action"`
Features []*geojson.Feature `json:"features"`
}
var m *melody.Melody
// InitMelody sets up the websocket handler.
func InitMelody() *melody.Melody {
m = melody.New()
// Incoming message about updated query params.
m.HandleConnect(func(s *melody.Session) {
log.Println("[websocket] connected", s.Request.RemoteAddr)
for _, v := range lastPushTTLCache.Items() {
features := v.Value()
bc := broadcats{
Action: websocketActionPopulate,
Features: features,
}
b, _ := json.Marshal(bc)
s.Write(b)
}
})
m.HandleDisconnect(func(s *melody.Session) {
log.Println("[websocket] disconnected", s.Request.RemoteAddr)
})
m.HandleError(func(s *melody.Session, e error) {
log.Println("[websocket] error", e, s.Request.RemoteAddr)
})
m.HandleMessage(messageHandler)
return m
}
// GetMelody does stuff
func GetMelody() *melody.Melody {
return m
}
// on request
func messageHandler(s *melody.Session, msg []byte) {
log.Println("[websocket] message", string(msg))
}
// on message
// on connect?