Files
tecamino-dbm/websocket/clientHandler.go
2025-07-25 18:26:36 +02:00

78 lines
1.6 KiB
Go

package websocket
import (
"encoding/json"
"fmt"
"sync"
"github.com/gin-gonic/gin"
"github.com/tecamino/tecamino-dbm/websocket/models"
wsModels "github.com/tecamino/tecamino-dbm/websocket/models"
json_dataModels "github.com/tecamino/tecamino-json_data/models"
)
// serves as connection handler of websocket
type ClientHandler struct {
sync.RWMutex
Clients models.Clients
}
func SendBroadcast(msg []byte) {
for _, c := range models.Broadcast {
c.SendResponse(msg)
}
}
// initaiates new conections with client map
func NewConnectionHandler() *ClientHandler {
return &ClientHandler{
Clients: make(models.Clients),
}
}
// Connect a recieving websocket connection
func (cH *ClientHandler) ConnectNewClient(id string, c *gin.Context) (client *models.Client, err error) {
if _, exists := cH.Clients[id]; exists {
return cH.Clients[id], nil
}
client, err = models.ConnectNewClient(id, c)
client.OnClose = func(code int, reason string) {
fmt.Println(23, "closing", id)
delete(cH.Clients, id)
}
if err != nil {
return nil, err
}
cH.Lock()
cH.Clients[id] = client
cH.Unlock()
return client, nil
}
// get client client
func (c *ClientHandler) GetClient(id string) *wsModels.Client {
if client, ok := c.Clients[id]; ok {
return client
}
return nil
}
// sends json response to client
func (c *ClientHandler) SendResponse(id string, r *json_dataModels.Response) error {
client, ok := c.Clients[id]
if !ok {
return fmt.Errorf("client not found for id %s", id)
}
b, err := json.Marshal(*r)
if err != nil {
return err
}
client.SendResponse(b)
return nil
}