2024-10-19 09:47:56 +00:00
|
|
|
package websocket
|
|
|
|
|
|
|
|
import (
|
|
|
|
"github.com/gorilla/websocket"
|
|
|
|
"net/http"
|
2024-11-20 19:31:24 +00:00
|
|
|
"time"
|
2024-10-28 08:33:05 +00:00
|
|
|
|
2024-11-04 19:33:25 +00:00
|
|
|
"git.smsvc.net/pomodoro/GoTomato/internal/helper"
|
2024-10-28 08:33:05 +00:00
|
|
|
"git.smsvc.net/pomodoro/GoTomato/pkg/models"
|
2024-10-19 09:47:56 +00:00
|
|
|
)
|
|
|
|
|
2024-10-30 06:37:14 +00:00
|
|
|
// Upgrade HTTP requests to WebSocket connections
|
2024-10-19 09:47:56 +00:00
|
|
|
var upgrader = websocket.Upgrader{
|
|
|
|
CheckOrigin: func(r *http.Request) bool { return true },
|
|
|
|
}
|
|
|
|
|
2024-10-30 06:37:14 +00:00
|
|
|
// Upgrades HTTP requests to WebSocket connections and manages the client lifecycle
|
2024-10-29 17:49:00 +00:00
|
|
|
func HandleConnection(w http.ResponseWriter, r *http.Request) {
|
2024-10-19 09:47:56 +00:00
|
|
|
// Upgrade initial GET request to a WebSocket
|
|
|
|
ws, err := upgrader.Upgrade(w, r, nil)
|
|
|
|
if err != nil {
|
2024-11-04 19:33:25 +00:00
|
|
|
helper.Logger.Error("WebSocket upgrade error:", "msg", err)
|
2024-10-19 09:47:56 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
defer ws.Close()
|
|
|
|
|
|
|
|
// Register the new client
|
2024-10-30 08:57:09 +00:00
|
|
|
client := models.WebsocketClient{
|
2024-11-20 19:26:04 +00:00
|
|
|
Conn: ws,
|
|
|
|
LastPong: time.Now(),
|
|
|
|
RealIP: r.RemoteAddr,
|
2024-10-20 09:06:37 +00:00
|
|
|
}
|
2024-11-20 20:52:08 +00:00
|
|
|
client.Conn.SetPongHandler(func(s string) error {
|
2024-11-20 20:22:12 +00:00
|
|
|
client.LastPong = time.Now()
|
|
|
|
return nil
|
|
|
|
})
|
|
|
|
|
2024-10-30 07:09:41 +00:00
|
|
|
mu.Lock()
|
2024-10-30 09:17:24 +00:00
|
|
|
Clients[ws.LocalAddr()] = &client
|
2024-10-20 15:31:05 +00:00
|
|
|
mu.Unlock()
|
2024-10-19 09:47:56 +00:00
|
|
|
|
2024-11-04 19:33:25 +00:00
|
|
|
helper.Logger.Info("Client connected", "host", client.RealIP, "clients", len(Clients))
|
2024-11-03 09:00:14 +00:00
|
|
|
|
2024-10-19 09:47:56 +00:00
|
|
|
// Listen for commands from the connected client
|
2024-10-30 07:09:41 +00:00
|
|
|
handleClientCommands(client)
|
2024-10-19 09:47:56 +00:00
|
|
|
}
|