animated-sniffle/app/echo.go

50 lines
821 B
Go
Raw Normal View History

2022-07-27 11:28:07 +03:00
package main
import (
"net/http"
2022-08-07 14:18:21 +03:00
"github.com/gorilla/websocket"
2022-07-27 11:28:07 +03:00
)
2022-08-07 14:18:21 +03:00
var (
wsClients = make(map[*websocket.Conn]struct{})
ws = struct {
Count chan int
Send chan []byte
Add chan *websocket.Conn
}{
Count: make(chan int, 100),
Send: make(chan []byte, 100),
Add: make(chan *websocket.Conn, 100),
2022-07-27 11:28:07 +03:00
}
2022-08-07 14:18:21 +03:00
)
2022-07-27 11:28:07 +03:00
2022-08-07 14:18:21 +03:00
func broadcast() {
2022-07-27 11:28:07 +03:00
for {
select {
2022-08-07 14:18:21 +03:00
case conn := <-ws.Add:
wsClients[conn] = struct{}{}
2022-07-27 11:28:07 +03:00
2022-08-07 14:18:21 +03:00
case <-ws.Count:
ws.Count <- len(wsClients)
2022-07-27 11:28:07 +03:00
2022-08-07 14:18:21 +03:00
case message := <-ws.Send:
for conn := range wsClients {
if err := conn.WriteMessage(1, message); err != nil {
conn.Close()
delete(wsClients, conn)
}
}
2022-07-27 11:28:07 +03:00
}
}
}
2022-08-07 14:18:21 +03:00
func wsHandler(w http.ResponseWriter, r *http.Request) {
2022-07-27 11:28:07 +03:00
conn, err := websocket.Upgrade(w, r, w.Header(), 1024, 1024)
if err != nil {
return
}
2022-08-07 14:18:21 +03:00
ws.Add <- conn
2022-07-27 11:28:07 +03:00
}