package go_web_gin import ( "log" "git.hujye.com/infrastructure/go-web-gin/config" "git.hujye.com/infrastructure/go-web-gin/database" "git.hujye.com/infrastructure/go-web-gin/logger" "git.hujye.com/infrastructure/go-web-gin/svr" "github.com/gin-gonic/gin" "github.com/redis/go-redis/v9" "gorm.io/gorm" ) // App represents the application type App struct { engine *gin.Engine db *gorm.DB rdb *redis.Client logger *logger.Logger } // New creates a new App instance and loads config file func New() *App { // Load config file if _, err := config.Load(); err != nil { log.Printf("Warning: failed to load config file, using defaults: %v", err) } return &App{ engine: svr.GetEngine(), logger: logger.GetLogger(), } } // UseMiddleware registers global middleware func (a *App) UseMiddleware(middleware ...gin.HandlerFunc) { a.engine.Use(middleware...) } // RegisterRoutes registers routes with the given handler function func (a *App) RegisterRoutes(registerFunc func(*gin.Engine)) { registerFunc(a.engine) } // InitMySQL initializes the MySQL database connection func (a *App) InitMySQL() *gorm.DB { a.db = database.GetDB() return a.db } // DB returns the gorm.DB instance func (a *App) DB() *gorm.DB { return a.db } // InitRedis initializes the Redis connection func (a *App) InitRedis() *redis.Client { a.rdb = database.GetRedis() return a.rdb } // Redis returns the redis.Client instance func (a *App) Redis() *redis.Client { return a.rdb } // Logger returns the logger.Logger instance func (a *App) Logger() *logger.Logger { return a.logger } // Run starts the application server func (a *App) Run(addr ...string) error { listenAddr := config.Get().GetAddr() // Non-production: use provided address if given, otherwise use config if !config.Get().IsRelease() && len(addr) > 0 && addr[0] != "" { listenAddr = addr[0] } a.logger.Info(nil, "Server starting", "addr", listenAddr, "mode", config.Get().Server.Mode) return a.engine.Run(listenAddr) }