mirror of
https://github.com/0ceanSlim/grain.git
synced 2024-11-22 08:37:13 +00:00
65 lines
1.3 KiB
Go
65 lines
1.3 KiB
Go
package relay
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"grain/relay/handlers"
|
|
"grain/relay/utils"
|
|
|
|
"golang.org/x/net/websocket"
|
|
)
|
|
|
|
func WebSocketHandler(ws *websocket.Conn) {
|
|
defer ws.Close()
|
|
|
|
var msg string
|
|
rateLimiter := utils.GetRateLimiter()
|
|
|
|
for {
|
|
err := websocket.Message.Receive(ws, &msg)
|
|
if err != nil {
|
|
fmt.Println("Error receiving message:", err)
|
|
return
|
|
}
|
|
fmt.Println("Received message:", msg)
|
|
|
|
if allowed, msg := rateLimiter.AllowWs(); !allowed {
|
|
websocket.Message.Send(ws, fmt.Sprintf(`{"error": "%s"}`, msg))
|
|
return
|
|
}
|
|
|
|
var message []interface{}
|
|
err = json.Unmarshal([]byte(msg), &message)
|
|
if err != nil {
|
|
fmt.Println("Error parsing message:", err)
|
|
continue
|
|
}
|
|
|
|
if len(message) < 2 {
|
|
fmt.Println("Invalid message format")
|
|
continue
|
|
}
|
|
|
|
messageType, ok := message[0].(string)
|
|
if !ok {
|
|
fmt.Println("Invalid message type")
|
|
continue
|
|
}
|
|
|
|
switch messageType {
|
|
case "EVENT":
|
|
handlers.HandleEvent(ws, message)
|
|
case "REQ":
|
|
if allowed, msg := rateLimiter.AllowReq(); !allowed {
|
|
websocket.Message.Send(ws, fmt.Sprintf(`{"error": "%s"}`, msg))
|
|
return
|
|
}
|
|
handlers.HandleReq(ws, message)
|
|
case "CLOSE":
|
|
handlers.HandleClose(ws, message)
|
|
default:
|
|
fmt.Println("Unknown message type:", messageType)
|
|
}
|
|
}
|
|
}
|