WebSocketServer/main.go

82 lines
1.9 KiB
Go

package main
import (
"os"
"time"
"clickandjoin.app/websocketserver/modules/config"
"clickandjoin.app/websocketserver/modules/rabbitmq"
"clickandjoin.app/websocketserver/modules/redis"
"clickandjoin.app/websocketserver/modules/scylladb"
"clickandjoin.app/websocketserver/modules/structs"
"clickandjoin.app/websocketserver/modules/utils"
"clickandjoin.app/websocketserver/socketserver"
gocnjhelper "git.clickandjoin.umbach.dev/ClickandJoin/go-cnj-helper"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/websocket/v2"
)
func init() {
config.LoadConfig()
gocnjhelper.InitLogger(config.Cfg.Debug, true, true)
scylladb.InitDatabase()
redis.Init()
go rabbitmq.Init()
}
func main() {
app := fiber.New()
// wait so that rabbitmq can connect
// TODO: better way to handle this
time.Sleep(500 * time.Millisecond)
app.Use("/", func(c *fiber.Ctx) error {
// IsWebSocketUpgrade returns true if the client
// requested upgrade to the WebSocket protocol.
if websocket.IsWebSocketUpgrade(c) {
wsSessionId := c.Query("auth")
// no auth query available
if len(wsSessionId) != utils.LenWebSocketSession {
return c.SendStatus(fiber.StatusUnauthorized)
}
// validate ws session
foundWsSession := structs.UserWebSocketSession{Id: wsSessionId}
q := scylladb.Session.Query(scylladb.WebSocketSessions.Get("id", "user_id")).BindStruct(foundWsSession)
if err := q.GetRelease(&foundWsSession); err != nil {
gocnjhelper.LogDebugf("Failed to find ws session: %s, err: %s", wsSessionId, err)
return c.SendStatus(fiber.StatusUnauthorized)
}
// TODO: Further security checks such as the change of IP, user agents
c.Locals("wsSessionId", wsSessionId)
c.Locals("userId", foundWsSession.UserId)
return c.Next()
}
return fiber.ErrUpgradeRequired
})
go socketserver.RunHub()
socketserver.WebSocketServer(app)
if len(os.Args) < 2 {
gocnjhelper.LogFatal("Please specify port")
}
app.Listen("127.0.0.1:" + os.Args[1])
}