-
Notifications
You must be signed in to change notification settings - Fork 0
/
websocket.go
67 lines (53 loc) · 1.16 KB
/
websocket.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
62
63
64
65
66
67
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
)
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
func wshandler(w http.ResponseWriter, r *http.Request) {
incrementalUpdates := (r.URL.Query().Get("diffs") == "true")
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
fmt.Println("Failed to set websocket upgrade: %+v", err)
return
}
p := NewPoller(incrementalUpdates)
go p.Poll()
commands := make(chan string)
go func() {
defer p.Close()
for {
data := make(map[string]string)
_, message, err := conn.ReadMessage()
if err != nil {
if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway) {
log.Printf("error: %v", err)
}
break
}
if err := json.Unmarshal(message, &data); err != nil {
log.Printf("error: %v", err)
}
if cmd, ok := data["command"]; ok {
commands <- cmd
}
}
}()
for {
select {
case status := <-p.Statuses:
conn.WriteJSON(status)
case err := <-p.Errors:
conn.WriteJSON(gin.H{"error": err.Error()})
case cmd := <-commands:
client.Cmd(cmd)
}
}
}