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