-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhub.go
More file actions
54 lines (44 loc) · 1.11 KB
/
Copy pathhub.go
File metadata and controls
54 lines (44 loc) · 1.11 KB
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
package im
import (
"log"
"sync"
"github.com/gorilla/websocket"
"github.com/tidwall/gjson"
)
// note: income data must be json as `{"event":"","msg":""}`
// event must be subscribe, unsubscriber, close or msg
func ServeMessages(conn *websocket.Conn) {
var mt sync.Mutex
for {
i, msg, err := conn.ReadMessage()
if err != nil {
log.Println("Error reading message no.", i)
conn.Close()
continue // return
}
// un/subscribe if event == un/subscribe.
income := gjson.ParseBytes(msg[1:])
event := income.Get("event").Str
data := income.Get("data").Raw
channel := income.Get("channel").Str
switch event {
case "message":
publish(i, channel, []byte(data))
case "subscribe":
subscribe(channel, conn)
msg = append([]byte("successfully subscribed to "), []byte(channel)...)
case "unsubscribe":
unsubscribe(channel, conn)
msg = append([]byte("successfully unsubscribed to "), []byte(channel)...)
default:
log.Println("unkown event: ", event)
}
mt.Lock()
if err = conn.WriteMessage(i, msg); err != nil {
log.Println(err)
mt.Unlock()
continue
}
mt.Unlock()
}
}