-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwebSocketHandlers.go
113 lines (89 loc) · 2.06 KB
/
webSocketHandlers.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
package main
import (
"github.com/gorilla/websocket"
"github.com/hpcloud/tail"
"log"
"net/http"
"time"
)
func createClientTailHandler(clients *SocketQueue, messages *[]*message) http.HandlerFunc {
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool {
log.Println("socket origin:", r.Host)
return true
},
}
return func(w http.ResponseWriter, r *http.Request) {
ws, err := upgrader.Upgrade(w, r, nil)
log.Println("new client")
if err != nil {
log.Println(err)
return
}
clients.Add(ws)
for _, message := range *messages {
err = ws.WriteJSON(message)
if err != nil {
break
}
}
}
}
func createClientStateHandler(stateClients *SocketQueue, tailers *map[string]*tail.Tail) http.HandlerFunc {
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool {
log.Println("socket origin:", r.Host)
return true
},
}
return func(w http.ResponseWriter, r *http.Request) {
ws, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Println(err)
return
}
log.Println("new state client")
stateClients.Add(ws)
keys := make([]string, 0, len(*tailers))
for k := range *tailers {
keys = append(keys, k)
}
err = ws.WriteJSON(keys)
if err != nil {
log.Println(err)
return
}
for {
time.Sleep(2 * time.Second)
keys := make([]string, 0, len(*tailers))
for k := range *tailers {
keys = append(keys, k)
}
err := ws.WriteJSON(keys)
if err != nil {
log.Printf("error when serving state: %v", err)
_ = ws.Close()
return
}
}
}
}
func handleMessages(clients *SocketQueue, broadcast *chan *message, messages *[]*message) {
for {
msg := <-*broadcast
*messages = append(*messages, msg)
for i, client := range clients.connections {
log.Printf("%s %s", client.LocalAddr().String(), i)
err := client.WriteJSON(msg)
if err != nil {
log.Printf("error: %v", err)
_ = client.Close()
go clients.Remove(client)
}
}
}
}