Files
mtusi2026lab2/app/internal/app.go
T

83 lines
2.2 KiB
Go
Executable File

package internal
import (
"errors"
"gitflic.ru/project/bulla-max/mtusi2026lab1/internal/chats"
"gitflic.ru/project/bulla-max/mtusi2026lab1/internal/common"
"gitflic.ru/project/bulla-max/mtusi2026lab1/internal/health"
"gitflic.ru/project/bulla-max/mtusi2026lab1/internal/messages"
"gitflic.ru/project/bulla-max/mtusi2026lab1/internal/storage"
"gitflic.ru/project/bulla-max/mtusi2026lab1/internal/users"
"github.com/gofiber/fiber/v3"
"github.com/gofiber/fiber/v3/middleware/recover"
"github.com/gofiber/fiber/v3/middleware/requestid"
"github.com/google/uuid"
)
func SignalGracefulShutdown() {
health.SignalShutdown()
}
func authMiddleware(c fiber.Ctx) error {
userIDStr := c.Get("X-User-Id")
if userIDStr == "" {
return common.SendError(c, fiber.StatusUnauthorized,
common.ErrorCodeUnauthorized, "X-User-Id header is required")
}
userID, err := uuid.Parse(userIDStr)
if err != nil {
return common.SendError(c, fiber.StatusBadRequest,
common.ErrorCodeInvalidRequest, "X-User-Id must be a valid UUID")
}
var exists bool
err = storage.GlobalStore.View(func(tx storage.ReadOnlyTx) error {
_, exists = tx.GetUser(userID)
return nil
})
if err != nil || !exists {
return common.SendError(c, fiber.StatusUnauthorized,
common.ErrorCodeUnauthorized, "user not found")
}
c.Locals("userID", userID)
return c.Next()
}
func GetApp() *fiber.App {
app := fiber.New(fiber.Config{
ErrorHandler: func(c fiber.Ctx, err error) error {
if appErr, ok := errors.AsType[*common.AppError](err); ok {
return common.SendError(c, appErr.Status, appErr.Code, appErr.Message)
}
if fiberErr, ok := errors.AsType[*fiber.Error](err); ok {
return common.SendError(c, fiberErr.Code,
common.ErrorCodeFromStatus(fiberErr.Code), fiberErr.Message)
}
return common.SendError(c, fiber.StatusInternalServerError,
common.ErrorCodeInternal, "Internal server error")
},
})
app.Use(recover.New())
app.Use(requestid.New())
health.RegisterRoutes(app.Group("/health"))
api := app.Group("/api/v1")
users.RegisterPublicRoutes(api)
protected := api.Group("")
protected.Use(authMiddleware)
users.RegisterRoutes(protected)
chats.RegisterRoutes(protected)
messages.RegisterRoutes(protected)
return app
}