WebSocketServer/main.go

80 lines
1.8 KiB
Go

package main
import (
"os"
"time"
"clickandjoin.app/websocketserver/modules/config"
"clickandjoin.app/websocketserver/modules/rabbitmq"
"clickandjoin.app/websocketserver/modules/scylladb"
"clickandjoin.app/websocketserver/modules/structs"
"clickandjoin.app/websocketserver/socketserver"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/websocket/v2"
"github.com/sirupsen/logrus"
)
func init() {
config.LoadConfig()
if config.Cfg.Debug {
logrus.SetLevel(logrus.DebugLevel)
}
logrus.Println("Debug:", config.Cfg.Debug)
scylladb.InitDatabase()
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) {
wsSession := c.Query("auth")
// no auth query available
if len(wsSession) == 0 {
return c.SendStatus(fiber.StatusUnauthorized)
}
// validate ws session
foundWsSession := structs.UserWebSocketSession{Id: wsSession}
q := scylladb.Session.Query(scylladb.WebSocketSessions.Get("id")).BindStruct(foundWsSession)
if err := q.GetRelease(&foundWsSession); err != nil {
logrus.Errorln("Failed to get ws session, err:", err)
return c.SendStatus(fiber.StatusInternalServerError)
}
// TODO: Further security checks such as the change of IP, user agents or whether the session ID has already opened another connection.
c.Locals("allowed", true)
return c.Next()
}
return fiber.ErrUpgradeRequired
})
go socketserver.RunHub()
socketserver.WebSocketServer(app)
if len(os.Args) < 2 {
logrus.Fatalln("Please specify port")
}
app.Listen("127.0.0.1:" + os.Args[1])
}