fix: prevent concurrent write to websocket connection
- refactor client handling and message broadcasting
- replace Client struct
- implement SendMessage method in Client struct for safer message sending
- update client map to use *models.Client instead of bool
- adjust BroadcastMessage and RunPomodoroTimer functions to use new client type
🤖
This commit is contained in:
parent
ffc6913344
commit
4471c86a0c
7 changed files with 53 additions and 17 deletions
|
@ -7,8 +7,3 @@ type BroadcastMessage struct {
|
|||
MaxSession int `json:"max_session"` // Total number of sessions
|
||||
TimeLeft int `json:"time_left"` // Remaining time in seconds
|
||||
}
|
||||
|
||||
// ClientCommand represents a command from the client (start/stop).
|
||||
type ClientCommand struct {
|
||||
Command string `json:"command"`
|
||||
}
|
30
pkg/models/client.go
Normal file
30
pkg/models/client.go
Normal file
|
@ -0,0 +1,30 @@
|
|||
package models
|
||||
|
||||
import (
|
||||
"github.com/gorilla/websocket"
|
||||
"log"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// ClientCommand represents a command from the client (start/stop).
|
||||
type ClientCommand struct {
|
||||
Command string `json:"command"`
|
||||
}
|
||||
|
||||
type Client struct {
|
||||
Conn *websocket.Conn
|
||||
Mutex sync.Mutex
|
||||
}
|
||||
|
||||
// It automatically locks and unlocks the mutex to ensure that only one goroutine can write at a time.
|
||||
func (c *Client) SendMessage(messageType int, data []byte) error {
|
||||
c.Mutex.Lock()
|
||||
defer c.Mutex.Unlock()
|
||||
|
||||
err := c.Conn.WriteMessage(messageType, data)
|
||||
if err != nil {
|
||||
log.Printf("Error writing to WebSocket: %v", err)
|
||||
c.Conn.Close() // Close the connection on error
|
||||
}
|
||||
return err
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue