feat: 添加服务和数据库初始化

This commit is contained in:
2026-03-02 23:30:00 +08:00
parent 607ff9a055
commit 52cfe1b911
9 changed files with 1091 additions and 33 deletions

55
app.go
View File

@@ -4,13 +4,20 @@ import (
"log"
"git.hujye.com/infrastructure/go-web-gin/config"
"git.hujye.com/infrastructure/go-web-gin/server"
"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 {
server *server.Server
engine *gin.Engine
db *gorm.DB
rdb *redis.Client
logger *logger.Logger
}
// New creates a new App instance and loads config file
@@ -21,21 +28,57 @@ func New() *App {
}
return &App{
server: server.New(),
engine: svr.GetEngine(),
logger: logger.GetLogger(),
}
}
// UseMiddleware registers global middleware
func (a *App) UseMiddleware(middleware ...gin.HandlerFunc) {
a.server.Engine().Use(middleware...)
a.engine.Use(middleware...)
}
// RegisterRoutes registers routes with the given handler function
func (a *App) RegisterRoutes(registerFunc func(*gin.Engine)) {
registerFunc(a.server.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 {
return a.server.Run(addr...)
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)
}