major change of websocket dbmHandler structure
This commit is contained in:
82
server/models/clients.go
Normal file
82
server/models/clients.go
Normal file
@@ -0,0 +1,82 @@
|
||||
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)
|
||||
}
|
Reference in New Issue
Block a user