105 lines
3.1 KiB
Go

package http
import (
"time"
"zee/internal/adapter/postgres"
"zee/internal/helper/config"
"zee/internal/helper/logger" // Added logger import
"zee/internal/service"
"zee/internal/transport/http/handler"
"zee/internal/transport/http/middleware"
"github.com/gin-gonic/gin"
"gorm.io/gorm"
)
// SetupRouter cấu hình router cho HTTP server
func SetupRouter(cfg *config.Config, db *gorm.DB) *gin.Engine {
// Khởi tạo router với mode phù hợp với môi trường
if cfg.App.Environment == "production" {
gin.SetMode(gin.ReleaseMode)
}
router := gin.New()
// Logger middleware
router.Use(middleware.Logger())
// Recovery middleware
router.Use(gin.Recovery())
// Apply security middleware
securityCfg := middleware.DefaultSecurityConfig()
securityCfg.Apply(router)
// Khởi tạo các handlers không phụ thuộc DB
healthHandler := handler.NewHealthHandler(cfg)
// Đăng ký các routes không phụ thuộc DB
router.GET("/ping", healthHandler.Ping)
router.GET("/health", healthHandler.HealthCheck)
// Các thành phần và routes phụ thuộc vào DB
if db != nil {
logger.Info("Database connection is available. Initializing DB-dependent services and routes...")
// Khởi tạo repositories
userRepo := postgres.NewUserRepository(db)
roleRepo := postgres.NewRoleRepository(db)
// Get JWT configuration from config
jwtSecret := "your-secret-key" // Default fallback
accessTokenExpire := 24 * time.Hour
// Override with config values if available
if cfg.JWT.Secret != "" {
jwtSecret = cfg.JWT.Secret
}
if cfg.JWT.AccessTokenExpire > 0 {
accessTokenExpire = time.Duration(cfg.JWT.AccessTokenExpire) * time.Minute
}
// Khởi tạo services
authSvc := service.NewAuthService(
userRepo,
roleRepo,
jwtSecret,
accessTokenExpire,
)
// Khởi tạo middleware
authMiddleware := middleware.NewAuthMiddleware(authSvc)
// Khởi tạo các handlers phụ thuộc DB
authHandler := handler.NewAuthHandler(authSvc)
// Auth routes (public)
authGroup := router.Group("/api/v1/auth")
{
authGroup.POST("/register", authHandler.Register)
authGroup.POST("/login", authHandler.Login)
authGroup.POST("/refresh", authHandler.RefreshToken)
authGroup.POST("/logout", authMiddleware.Authenticate(), authHandler.Logout)
}
// Protected API routes
api := router.Group("/api/v1")
api.Use(authMiddleware.Authenticate())
{
// Ví dụ về protected endpoints
// api.GET("/profile", userHandler.GetProfile)
// api.PUT("/profile", userHandler.UpdateProfile)
}
} else {
logger.Info("Database is disabled via feature flag or connection failed. DB-dependent routes (e.g., /api/v1/auth, /api/v1/*) will not be available.")
// Optionally, register placeholder routes that return 503 Service Unavailable
// router.Any("/api/v1/auth/*any", func(c *gin.Context) {
// c.JSON(http.StatusServiceUnavailable, gin.H{"error": "Authentication service is currently disabled"})
// })
// router.Any("/api/v1/*any", func(c *gin.Context) {
// c.JSON(http.StatusServiceUnavailable, gin.H{"error": "API service is currently disabled due to database unavailability"})
// })
}
return router
}