make json abstraction for server

This commit is contained in:
Adrian Zuercher
2025-04-15 11:04:14 +02:00
parent 3d1dee25f1
commit a1f947e24a
6 changed files with 149 additions and 130 deletions

49
server/clients.go Normal file
View File

@@ -0,0 +1,49 @@
package server
import (
"context"
"log"
"sync"
"github.com/coder/websocket"
"github.com/coder/websocket/wsjson"
"github.com/zuadi/tecamino-dbm.git/models"
)
var (
clients = make(map[*Client]bool)
clientsMu sync.Mutex
)
type Client struct {
conn *websocket.Conn
ctx context.Context
}
func registerClient(c *Client) {
clientsMu.Lock()
defer clientsMu.Unlock()
clients[c] = true
log.Printf("Client connected (%d total)", len(clients))
}
func unregisterClient(c *Client) {
clientsMu.Lock()
defer clientsMu.Unlock()
delete(clients, c)
log.Printf("Client disconnected (%d total)", len(clients))
}
func broadcast(data models.JsonData) {
clientsMu.Lock()
defer clientsMu.Unlock()
for c := range clients {
go func(client *Client) {
err := wsjson.Write(client.ctx, client.conn, data)
if err != nil {
log.Printf("Broadcast error: %v", err)
}
}(c)
}
}