abstract write to websocket and add request id

This commit is contained in:
Adrian Zürcher
2025-05-01 12:51:35 +02:00
parent 8e6b39c8bf
commit 4b36598bd7
4 changed files with 107 additions and 27 deletions

View File

@@ -1,10 +1,15 @@
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"
)
type Connections struct {
@@ -30,3 +35,30 @@ func (c *Connections) RemoveClient(id string) {
func (c *Connections) DisconnectWsConnection(id string, code websocket.StatusCode, reason string) {
c.Clients.DisconnectWsConnection(id, code, reason)
}
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 " + 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
}