-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathcomment_socket.go
More file actions
71 lines (65 loc) · 1.69 KB
/
comment_socket.go
File metadata and controls
71 lines (65 loc) · 1.69 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package main
import (
"encoding/json"
"fmt"
)
const (
SocketMessageTypeConfig = "config"
SocketMessageTypeSession = "session"
)
var wsInCh chan string = make(chan string, 10)
var wsOutCh chan string = make(chan string, 10)
type SocketMessage struct {
Type string `json:"type"`
Seq string `json:"seq"`
Payload interface{} `json:"payload"`
Error string `json:"error"`
}
func handleSocketMessage(message string) {
var msg SocketMessage
err := json.Unmarshal([]byte(message), &msg)
if err != nil {
return
}
switch msg.Type {
case SocketMessageTypeConfig:
response := SocketMessage{Type: SocketMessageTypeConfig, Seq: msg.Seq}
if msg.Payload != nil {
newConfig, err := NewConfigFromMap(msg.Payload.(map[string]interface{}))
if err != nil {
response.Error = fmt.Errorf("invalid config data, %w", err).Error()
} else {
applyConfig(newConfig)
}
}
response.Payload = config
sendSocket(response)
case SocketMessageTypeSession:
response := SocketMessage{Type: SocketMessageTypeSession, Seq: msg.Seq}
if msg.Payload != nil {
m := msg.Payload.(map[string]interface{})
ts, ok := m["timestamps"]
if ok {
err := session.Timestamps.UpdateFromJSON(ts.(map[string]interface{}))
if err != nil {
response.Error = fmt.Errorf("invalid session data, failed to parse timestamps: %w", err).Error()
}
}
}
response.Payload = session
sendSocket(response)
}
}
func sendSocket(message SocketMessage) error {
outMsgBytes, err := json.Marshal(message)
if err != nil {
return err
}
select {
case wsOutCh <- string(outMsgBytes):
// nothing
default:
// fmt.Println("Websocket output channel is full, dropping message")
}
return nil
}