implement new json_data model

This commit is contained in:
Adrian Zürcher
2025-04-29 08:31:06 +02:00
parent 0a137c9d86
commit 49d8d03d8a
25 changed files with 609 additions and 572 deletions

View File

@@ -3,7 +3,7 @@ package models
import (
"context"
"fmt"
"net/http"
"time"
"github.com/coder/websocket"
"github.com/gin-gonic/gin"
@@ -14,8 +14,10 @@ var Origins []string = []string{"*"}
type Clients map[string]*Client
type Client struct {
Connected *bool `json:"connected"`
Conn *websocket.Conn `json:"-"`
Ctx context.Context `json:"-"`
Cancel context.CancelFunc `json:"-"`
Connected bool `json:"connected"`
Conn *websocket.Conn `json:"-"`
}
func NewClients() Clients {
@@ -23,60 +25,35 @@ func NewClients() Clients {
}
// Connect a recieving websocket connection
func (c *Clients) ConnectRecievingWsConnection(id string, ctx *gin.Context) error {
if _, exists := (*c)[id]; exists {
func (cl *Clients) ConnectRecievingWsConnection(id string, c *gin.Context) error {
if _, exists := (*cl)[id]; exists {
return nil
}
conn, err := websocket.Accept(ctx.Writer, ctx.Request, &websocket.AcceptOptions{
conn, err := websocket.Accept(c.Writer, c.Request, &websocket.AcceptOptions{
OriginPatterns: Origins,
})
if err != nil {
return fmt.Errorf("error accept websocket client: %s", err)
}
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute)
b := true
(*c)[id] = &Client{
Connected: &b,
(*cl)[id] = &Client{
Connected: true,
Ctx: ctx,
Cancel: cancel,
Conn: conn,
}
return nil
}
// Connect a recieving websocket connection
func (c *Clients) ConnectSendingWsConnection(id, url string) (*websocket.Conn, error) {
if _, exists := (*c)[id]; exists {
return (*c)[id].Conn, nil
}
header := http.Header{}
header.Set("Authorization", "Bearer "+id)
conn, _, err := websocket.Dial(context.Background(), url, &websocket.DialOptions{
HTTPHeader: header,
})
if err != nil {
return nil, err
}
b := true
(*c)[id] = &Client{
Connected: &b,
Conn: conn,
}
return conn, nil
}
func (c *Clients) RemoveClient(id string) {
delete(*c, id)
}
func (c *Clients) GetClientPointer(id string) *bool {
return (*c)[id].Connected
}
func (c *Clients) DisconnectWsConnection(id string, code websocket.StatusCode, reason string) {
*(*c)[id].Connected = false
(*c)[id].Connected = false
(*c)[id].Conn.Close(code, reason)
(*c)[id].Cancel()
}