forked from mtusi2026/mtusi2026lab3
73 lines
2.2 KiB
Go
Executable File
73 lines
2.2 KiB
Go
Executable File
package internal
|
|
|
|
import (
|
|
"errors"
|
|
"time"
|
|
|
|
"gitflic.ru/project/bulla-max/mtusi2026lab2/internal/auth"
|
|
"gitflic.ru/project/bulla-max/mtusi2026lab2/internal/chats"
|
|
"gitflic.ru/project/bulla-max/mtusi2026lab2/internal/common"
|
|
"gitflic.ru/project/bulla-max/mtusi2026lab2/internal/config"
|
|
"gitflic.ru/project/bulla-max/mtusi2026lab2/internal/health"
|
|
"gitflic.ru/project/bulla-max/mtusi2026lab2/internal/messages"
|
|
"gitflic.ru/project/bulla-max/mtusi2026lab2/internal/session"
|
|
"gitflic.ru/project/bulla-max/mtusi2026lab2/internal/store"
|
|
"gitflic.ru/project/bulla-max/mtusi2026lab2/internal/users"
|
|
"github.com/gofiber/fiber/v3"
|
|
"github.com/gofiber/fiber/v3/middleware/recover"
|
|
"github.com/gofiber/fiber/v3/middleware/requestid"
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
)
|
|
|
|
func SignalGracefulShutdown() {
|
|
health.SignalShutdown()
|
|
}
|
|
|
|
func New(cfg config.Config, pool *pgxpool.Pool, sessions *session.Store) *fiber.App {
|
|
st := store.New(pool, cfg.DBTimeout)
|
|
|
|
app := fiber.New(fiber.Config{
|
|
ReadTimeout: 10 * time.Second,
|
|
WriteTimeout: 10 * time.Second,
|
|
IdleTimeout: 60 * time.Second,
|
|
BodyLimit: 1 * 1024 * 1024,
|
|
ErrorHandler: handleError,
|
|
})
|
|
|
|
app.Use(recover.New())
|
|
app.Use(requestid.New())
|
|
|
|
health.RegisterRoutes(app.Group("/health"), st, sessions)
|
|
|
|
api := app.Group("/api/v1")
|
|
users.RegisterPublicRoutes(api, st)
|
|
auth.RegisterPublicRoutes(api, st, sessions)
|
|
|
|
protected := api.Group("")
|
|
protected.Use(auth.BearerAuth(sessions))
|
|
auth.RegisterProtectedRoutes(protected, st, sessions)
|
|
users.RegisterProtectedRoutes(protected, st)
|
|
chats.RegisterProtectedRoutes(protected, st)
|
|
messages.RegisterProtectedRoutes(protected, st)
|
|
|
|
return app
|
|
}
|
|
|
|
// handleError keeps every failure in the contract error envelope, including
|
|
// Fiber's own errors (404, 405, 413) and recovered panics.
|
|
func handleError(c fiber.Ctx, err error) error {
|
|
var appErr *common.AppError
|
|
if errors.As(err, &appErr) {
|
|
return common.SendError(c, appErr.Status, appErr.Code, appErr.Message)
|
|
}
|
|
|
|
var fiberErr *fiber.Error
|
|
if errors.As(err, &fiberErr) {
|
|
return common.SendError(c, fiberErr.Code,
|
|
common.ErrorCodeFromStatus(fiberErr.Code), fiberErr.Message)
|
|
}
|
|
|
|
return common.SendError(c, fiber.StatusInternalServerError,
|
|
common.ErrorCodeInternal, "Internal server error")
|
|
}
|