forked from MikaBot/cluster-operator
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
relay.go
65 lines (60 loc) · 1.16 KB
/
relay.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
package main
import (
"github.com/gorilla/websocket"
"net/http"
"sync"
)
type RelayHandler struct {
mutex *sync.RWMutex
clients map[string]*websocket.Conn
}
func (rh *RelayHandler) putClient(id string, con *websocket.Conn) {
rh.mutex.Lock()
rh.clients[id] = con
rh.mutex.Unlock()
}
func (rh *RelayHandler) deleteClient(id string) {
rh.mutex.Lock()
delete(rh.clients, id)
rh.mutex.Unlock()
}
func (rh *RelayHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
client, err := Server.Upgrader.Upgrade(w, r, nil)
if err != nil {
return
}
if r.Header.Get("authorization") == "" || r.Header.Get("authorization") != Config.Auth {
_ = client.Close()
return
}
id := RandomID()
if id == "" {
return
}
rh.putClient(id, client)
go func() {
for {
packet := Packet{}
err := client.ReadJSON(&packet)
if err != nil {
rh.deleteClient(id)
return
}
// Type 0 is dispatch
// Type 1 is receive
if packet.Type == 0 {
rh.mutex.RLock()
for i, c := range rh.clients {
if i == id {
continue
}
_ = c.WriteJSON(Packet{
Type: 1,
Body: packet.Body,
})
}
rh.mutex.RUnlock()
}
}
}()
}