move pong handler to connection handler

This commit is contained in:
Sebastian Mark 2024-11-20 20:24:15 +01:00
parent 6f60423c03
commit 5f8c818118
2 changed files with 7 additions and 4 deletions

View file

@ -5,6 +5,7 @@ import (
"net" "net"
"net/http" "net/http"
"sync" "sync"
"time"
"git.smsvc.net/pomodoro/GoTomato/internal/helper" "git.smsvc.net/pomodoro/GoTomato/internal/helper"
"git.smsvc.net/pomodoro/GoTomato/pkg/models" "git.smsvc.net/pomodoro/GoTomato/pkg/models"
@ -34,6 +35,12 @@ func HandleConnection(w http.ResponseWriter, r *http.Request) {
Conn: ws, Conn: ws,
RealIP: r.RemoteAddr, RealIP: r.RemoteAddr,
} }
client.Conn.SetPongHandler(func(s string) error {
client.LastPong = time.Now()
return nil
})
mu.Lock() mu.Lock()
Clients[ws.LocalAddr()] = &client Clients[ws.LocalAddr()] = &client
mu.Unlock() mu.Unlock()

View file

@ -25,10 +25,6 @@ type WebsocketClient struct {
// Sends a message to the websocket. // Sends a message to the websocket.
// Automatically locks and unlocks the client mutex, to ensure that only one goroutine can write at a time. // Automatically locks and unlocks the client mutex, to ensure that only one goroutine can write at a time.
func (c *WebsocketClient) SendMessage(messageType int, data []byte) error { func (c *WebsocketClient) SendMessage(messageType int, data []byte) error {
c.Conn.SetPongHandler(func(s string) error {
c.LastPong = time.Now()
return nil
})
c.Conn.SetWriteDeadline(time.Now().Add(TIMEOUT * time.Second)) c.Conn.SetWriteDeadline(time.Now().Add(TIMEOUT * time.Second))
c.Conn.WriteMessage(websocket.PingMessage, nil) c.Conn.WriteMessage(websocket.PingMessage, nil)