-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathws.go
50 lines (42 loc) · 874 Bytes
/
ws.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
package main
import (
"log"
"github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
)
var upgrader = websocket.Upgrader{}
type wsServer struct {
clients map[*websocket.Conn]bool
broadcast chan []byte
register chan *websocket.Conn
}
var wss = wsServer{
clients: make(map[*websocket.Conn]bool),
broadcast: make(chan []byte),
register: make(chan *websocket.Conn),
}
func (wss *wsServer) run() {
for {
select {
case c := <-wss.register:
wss.clients[c] = true
case msg := <-wss.broadcast:
for c := range wss.clients {
err := c.WriteMessage(websocket.TextMessage, msg)
if err != nil {
delete(wss.clients, c)
c.Close()
}
}
}
}
}
func serveWs(c *gin.Context) {
w, r := c.Writer, c.Request
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Println("upgrade:", err)
return
}
wss.register <- conn
}