-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.go
More file actions
80 lines (69 loc) · 1.68 KB
/
Copy pathserver.go
File metadata and controls
80 lines (69 loc) · 1.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package rtgraph
import (
"encoding/json"
"fmt"
"github.com/gin-gonic/gin"
"github.com/minor-industries/rtgraph/assets"
"github.com/minor-industries/rtgraph/messages"
"github.com/minor-industries/rtgraph/subscription"
"net/http"
"nhooyr.io/websocket"
"time"
)
// SetupServer sets up all the routes
func (g *Graph) SetupServer(rg *gin.RouterGroup) {
rg.GET("/*filepath", func(c *gin.Context) {
filepath := c.Param("filepath")
switch filepath {
case "/ws":
g.handleWebSocket(c)
case "/":
c.Status(http.StatusNotFound)
default:
c.FileFromFS("rtgraph"+filepath, http.FS(assets.FS))
}
})
}
// Separate function to handle WebSocket connections
func (g *Graph) handleWebSocket(c *gin.Context) {
ctx := c.Request.Context()
conn, err := websocket.Accept(c.Writer, c.Request, &websocket.AcceptOptions{
InsecureSkipVerify: true,
})
if err != nil {
_ = c.AbortWithError(http.StatusInternalServerError, err)
return
}
defer func() {
_ = conn.Close(websocket.StatusInternalError, "Closed unexpectedly")
}()
_, reqBytes, err := conn.Read(ctx)
if err != nil {
fmt.Println("ws read error", err.Error())
return
}
conn.CloseRead(ctx)
var req subscription.Request
err = json.Unmarshal(reqBytes, &req)
if err != nil {
fmt.Println("ws error", err.Error())
return
}
msgCh := make(chan *messages.Data)
now := time.Now()
go func() {
g.Subscribe(&req, now, msgCh)
close(msgCh)
}()
for data := range msgCh {
binmsg, err := data.MarshalMsg(nil)
if err != nil {
fmt.Println("marshal msg error", err)
return
}
if err := conn.Write(ctx, websocket.MessageBinary, binmsg); err != nil {
fmt.Println("write binary to websocket error", err)
return
}
}
}