abstract write to websocket and add request id
This commit is contained in:
@@ -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
|
||||
}
|
||||
|
Reference in New Issue
Block a user