68 lines
1.4 KiB
Go
68 lines
1.4 KiB
Go
package models
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"sync"
|
|
"time"
|
|
|
|
"github.com/coder/websocket"
|
|
"github.com/gin-gonic/gin"
|
|
json_dataModels "github.com/tecamino/tecamino-json_data/models"
|
|
)
|
|
|
|
// serves as connection handler of websocket
|
|
type Connections struct {
|
|
sync.RWMutex
|
|
Clients Clients
|
|
}
|
|
|
|
// initaiates new conections with client map
|
|
func NewConnections() *Connections {
|
|
return &Connections{
|
|
Clients: NewClients(),
|
|
}
|
|
}
|
|
|
|
// Connect a recieving websocket connection
|
|
func (c *Connections) ConnectRecievingWsConnection(id string, ctx *gin.Context) error {
|
|
return c.Clients.ConnectRecievingWsConnection(id, ctx)
|
|
}
|
|
|
|
func (c *Connections) RemoveClient(id string) {
|
|
c.Clients.RemoveClient(id)
|
|
}
|
|
|
|
func (c *Connections) DisconnectWsConnection(id string, code websocket.StatusCode, reason string) {
|
|
c.Clients.DisconnectWsConnection(id, code, reason)
|
|
}
|
|
|
|
// sends json response to client
|
|
func (c *Connections) 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
|
|
}
|
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
|
defer cancel()
|
|
|
|
w, err := client.Conn.Writer(ctx, websocket.MessageText)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer w.Close()
|
|
|
|
_, err = w.Write(b)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return nil
|
|
}
|