92 lines
2.3 KiB
Go
92 lines
2.3 KiB
Go
package http
|
|
|
|
import (
|
|
"starter-kit/internal/adapter/persistence"
|
|
"starter-kit/internal/helper/config"
|
|
"starter-kit/internal/service"
|
|
"starter-kit/internal/transport/http/handler"
|
|
"starter-kit/internal/transport/http/middleware"
|
|
"time"
|
|
|
|
"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 repositories
|
|
userRepo := persistence.NewUserRepository(db)
|
|
roleRepo := persistence.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)
|
|
_ = authMiddleware // TODO: Use authMiddleware when needed
|
|
|
|
// Khởi tạo các handlers
|
|
healthHandler := handler.NewHealthHandler(cfg)
|
|
authHandler := handler.NewAuthHandler(authSvc)
|
|
|
|
// Đăng ký các routes
|
|
|
|
// Health check routes (public)
|
|
router.GET("/ping", healthHandler.Ping)
|
|
router.GET("/health", healthHandler.HealthCheck)
|
|
|
|
// 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)
|
|
}
|
|
|
|
return router
|
|
}
|