-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathws.go
111 lines (94 loc) · 2.35 KB
/
ws.go
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
package altcrawlhqserver
import (
"encoding/json"
"fmt"
"net/http"
"time"
"github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
"github.com/internetarchive/gocrawlhq"
"github.com/jellydator/ttlcache/v3"
)
var onlineClientsStats = ttlcache.New[string, gocrawlhq.IdentifyMessage](
ttlcache.WithTTL[string, gocrawlhq.IdentifyMessage](time.Minute*1),
ttlcache.WithDisableTouchOnHit[string, gocrawlhq.IdentifyMessage](),
)
func init() {
fmt.Println("Initializing onlineClientsStats...")
go onlineClientsStats.Start()
fmt.Println("Initialized onlineClientsStats!")
}
func onlineClientsHandler(c *gin.Context) {
if !isAuthorized(c) {
c.JSON(http.StatusUnauthorized, gin.H{
"error": "Unauthorized",
})
return
}
clients := make([]gocrawlhq.IdentifyMessage, 0)
for _, client := range onlineClientsStats.Items() {
clients = append(clients, client.Value())
}
c.JSON(http.StatusOK, clients)
}
func websocketHandler(c *gin.Context) {
if !isAuthorized(c) {
c.JSON(http.StatusUnauthorized, gin.H{
"error": "Unauthorized",
})
return
}
upGrader := websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true
},
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
ws, err := upGrader.Upgrade(c.Writer, c.Request, nil)
if err != nil {
panic(err)
}
defer func() {
closeSocketErr := ws.Close()
if closeSocketErr != nil {
panic(err)
}
}()
for {
wsMsgType, wsMsg, err := ws.ReadMessage()
if err != nil {
panic(err)
}
fmt.Printf("Message Type: %d, Message: %s\n", wsMsgType, string(wsMsg))
if wsMsgType != websocket.TextMessage {
panic("Message type is not text")
}
// {"type":"identify","payload":`+string(marshalled)+`}`
msgType := struct {
Type string `json:"type"`
}{}
if err := json.Unmarshal(wsMsg, &msgType); err != nil {
panic(err)
}
if msgType.Type != "identify" {
panic("Message type is not identify")
}
identifyMessage := struct {
Payload gocrawlhq.IdentifyMessage `json:"payload"`
}{}
if err := json.Unmarshal(wsMsg, &identifyMessage); err != nil {
panic(err)
}
onlineClientsStats.Set(identifyMessage.Payload.Identifier, identifyMessage.Payload, ttlcache.DefaultTTL)
fmt.Printf("Identify Message: %+v\n", identifyMessage)
err = ws.WriteJSON(struct {
Reply string `json:"reply"`
}{
Reply: "Echo...",
})
if err != nil {
panic(err)
}
}
}