GoTomato/internal/websocket/staleClients.go

46 lines
881 B
Go

package websocket
import (
"time"
"git.smsvc.net/pomodoro/GoTomato/pkg/models"
"github.com/gorilla/websocket"
)
func sendPing(client *models.WebsocketClient) bool {
client.Conn.SetWriteDeadline(time.Now().Add(10 * time.Second))
err := client.Conn.WriteMessage(websocket.PingMessage, nil)
if err != nil {
return false
}
return true
}
func isStale(client *models.WebsocketClient) bool {
return time.Since(client.LastPong) > (90 * time.Second)
}
// Check and remove stale clients
func RemoveStaleClients() {
ticker := time.NewTicker(30 * time.Second)
defer ticker.Stop()
for range ticker.C {
mu.Lock()
for _, client := range Clients {
if !sendPing(client) {
client.Conn.Close()
delete(Clients, client.Conn.LocalAddr())
}
if isStale(client) {
client.Conn.Close()
delete(Clients, client.Conn.LocalAddr())
}
}
mu.Unlock()
}
}