package models import ( "context" "fmt" "time" "github.com/coder/websocket" "github.com/gin-gonic/gin" ) var Origins []string = []string{"*"} type Clients map[string]*Client type Client struct { Ctx context.Context `json:"-"` Cancel context.CancelFunc `json:"-"` Connected bool `json:"connected"` Conn *websocket.Conn `json:"-"` } func NewClients() Clients { return make(Clients) } // Connect a recieving websocket connection func (cl *Clients) ConnectRecievingWsConnection(id string, c *gin.Context) error { if _, exists := (*cl)[id]; exists { return nil } 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) (*cl)[id] = &Client{ Connected: true, Ctx: ctx, Cancel: cancel, Conn: conn, } return nil } func (c *Clients) RemoveClient(id string) { delete(*c, id) } func (c *Clients) DisconnectWsConnection(id string, code websocket.StatusCode, reason string) { (*c)[id].Connected = false (*c)[id].Conn.Close(code, reason) (*c)[id].Cancel() }