52 lines
1.1 KiB
Go
52 lines
1.1 KiB
Go
package models
|
|
|
|
import (
|
|
"fmt"
|
|
|
|
"github.com/coder/websocket"
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
type Clients map[string]Client
|
|
|
|
type Client struct {
|
|
Connected *bool `json:"connected"`
|
|
SndConn *websocket.Conn `json:"-"` //sending connection
|
|
RvcConn *websocket.Conn `json:"-"` // revieving connection
|
|
}
|
|
|
|
func NewClients() Clients {
|
|
return make(Clients)
|
|
}
|
|
|
|
// Connect a recieving websocket connection
|
|
func (c *Clients) ConnectRecievingWsConnection(id string, ctx *gin.Context) (*websocket.Conn, error) {
|
|
conn, err := websocket.Accept(ctx.Writer, ctx.Request, &websocket.AcceptOptions{
|
|
OriginPatterns: []string{"*"},
|
|
})
|
|
|
|
if err != nil {
|
|
return nil, fmt.Errorf("error accept websocket client: %s", err)
|
|
}
|
|
|
|
b := true
|
|
(*c)[id] = Client{
|
|
Connected: &b,
|
|
RvcConn: 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) DisconnectRecievingWsConnection(id string, code websocket.StatusCode, reason string) {
|
|
*(*c)[id].Connected = false
|
|
(*c)[id].RvcConn.Close(code, reason)
|
|
}
|