29 lines
789 B
Go
29 lines
789 B
Go
|
package broadcast
|
||
|
|
||
|
import (
|
||
|
"encoding/json"
|
||
|
"git.smsvc.net/pomodoro/GoTomato/pkg/models"
|
||
|
"github.com/gorilla/websocket"
|
||
|
"log"
|
||
|
)
|
||
|
|
||
|
// BroadcastMessage sends a message to all connected WebSocket clients.
|
||
|
func BroadcastMessage(clients map[*websocket.Conn]bool, message models.BroadcastMessage) {
|
||
|
// Marshal the message into JSON format
|
||
|
jsonMessage, err := json.Marshal(message)
|
||
|
if err != nil {
|
||
|
log.Printf("Error marshalling message: %v", err)
|
||
|
return
|
||
|
}
|
||
|
|
||
|
// Iterate over all connected clients and broadcast the message
|
||
|
for client := range clients {
|
||
|
err := client.WriteMessage(websocket.TextMessage, jsonMessage)
|
||
|
if err != nil {
|
||
|
log.Printf("Error broadcasting to client: %v", err)
|
||
|
client.Close()
|
||
|
delete(clients, client) // Remove the client if an error occurs
|
||
|
}
|
||
|
}
|
||
|
}
|