GoTomato/internal/broadcast/broadcast.go
Sebastian Mark c59f737eb7 feat(server): restructure Pomodoro server into modular components
- move server logic to cmd/server/main.go
- create packages for websocket, pomodoro and broadcast handling
- define models for messages
- remove old GoTomato.go file
- update README

🤖
2024-10-19 16:49:09 +02:00

28 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
}
}
}