77 lines
1.5 KiB
Go
77 lines
1.5 KiB
Go
package websocket
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"sync"
|
|
|
|
"gitea.tecamino.com/paadi/tecamino-dbm/websocket/models"
|
|
wsModels "gitea.tecamino.com/paadi/tecamino-dbm/websocket/models"
|
|
json_dataModels "gitea.tecamino.com/paadi/tecamino-json_data/models"
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
// 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) {
|
|
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
|
|
}
|