special-pancake/app/echo.go

94 lines
1.5 KiB
Go
Raw Normal View History

2022-07-27 11:34:26 +03:00
package main
import (
2022-12-01 21:06:18 +03:00
"fmt"
"time"
2022-07-27 11:34:26 +03:00
"net/http"
"github.com/gorilla/websocket"
)
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool {
if r.Header.Get("origin") == "https://statbate.com" {
return true
}
return false
},
}
2022-07-27 11:34:26 +03:00
var (
wsClients = make(map[*websocket.Conn]struct{})
ws = struct {
Count chan int
Send chan []byte
Add chan *websocket.Conn
2022-12-01 21:06:18 +03:00
Del chan *websocket.Conn
2022-07-27 11:34:26 +03:00
}{
Count: make(chan int, 100),
Send: make(chan []byte, 100),
Add: make(chan *websocket.Conn, 100),
2022-12-01 21:06:18 +03:00
Del: make(chan *websocket.Conn, 100),
2022-07-27 11:34:26 +03:00
}
)
func broadcast() {
2022-12-01 21:06:18 +03:00
ticker := time.NewTicker(30 * time.Second)
2022-07-27 11:34:26 +03:00
for {
select {
case conn := <-ws.Add:
wsClients[conn] = struct{}{}
2022-12-01 21:06:18 +03:00
case conn := <-ws.Del:
delete(wsClients, conn)
2022-07-27 11:34:26 +03:00
case <-ws.Count:
ws.Count <- len(wsClients)
case message := <-ws.Send:
2022-12-01 21:06:18 +03:00
sendMessage(message)
case <-ticker.C:
sendMessage([]byte("ping"))
}
}
}
func sendMessage(message []byte) {
for conn := range wsClients {
if err := conn.WriteMessage(1, message); err != nil {
conn.Close()
delete(wsClients, conn)
2022-07-27 11:34:26 +03:00
}
}
}
func wsHandler(w http.ResponseWriter, r *http.Request) {
conn, err := upgrader.Upgrade(w, r, nil)
2022-07-27 11:34:26 +03:00
if err != nil {
return
}
2022-12-01 21:06:18 +03:00
go readWS(conn)
}
func readWS(conn *websocket.Conn) {
defer conn.Close()
2022-07-27 11:34:26 +03:00
ws.Add <- conn
2022-12-01 21:06:18 +03:00
defer func() {
ws.Del <- conn
}()
for {
_, _, err := conn.ReadMessage()
if err != nil {
fmt.Println("readWS", err.Error())
return
}
}
2022-07-27 11:34:26 +03:00
}