feat: Remove global db.Dbpool with dependency injection (Phase 0)

- Add Database struct in internal/db/database.go with Pool, Ctx, and RunMigrations()
- Update server.go to use Database struct with NewServerInstance()
- Add backend.go with InitBackend(), BackendRepo(), BackendCtx(), BackendPool()
- Update music.go and sync.go to use BackendRepo() and BackendCtx() instead of db.Dbpool/db.Ctx
- Update token_handler.go to accept pool parameter
- Update routes.go to use s.db.Pool for middleware
- Update cmd/main.go to use NewServerInstance() and HTTPServer()
- Update test_helpers.go to initialize backend with test database
- Update test files to use backend.BackendPool() and backend.BackendCtx()

Benefits:
- Easier to mock database for unit tests
- Follows Go best practices (dependency injection)
- Better architecture with explicit dependencies
- RunMigrations() replaces old Migrate_db() function

Note: Global db.Dbpool and db.Ctx still exist in dbHelper.go for backward compatibility
with test_helpers.go, but production code no longer uses them.

Generated by Mistral Vibe.
Co-Authored-By: Mistral Vibe <vibe@mistral.ai>
This commit is contained in:
2026-06-01 18:50:05 +02:00
parent 6cc014ffa3
commit 24a9111333
11 changed files with 320 additions and 100 deletions
+58 -25
View File
@@ -6,6 +6,7 @@ import (
"strconv"
"time"
"music-server/internal/backend"
"music-server/internal/db"
"music-server/internal/logging"
"net/http"
@@ -15,7 +16,9 @@ import (
type Server struct {
port int
db *db.Database
tokenHandler *TokenHandler
httpServer *http.Server
}
var (
@@ -30,7 +33,9 @@ var (
logJSON = os.Getenv("LOG_JSON") == "true"
)
func NewServer() *http.Server {
// NewServerInstance creates a new Server instance with all dependencies initialized.
// Use this for dependency injection and proper lifecycle management.
func NewServerInstance() *Server {
// Initialize logger
if logLevel == "" {
logLevel = "info"
@@ -40,15 +45,45 @@ func NewServer() *http.Server {
logger := logging.GetLogger()
port, _ := strconv.Atoi(os.Getenv("PORT"))
// Initialize token handler
tokenHandler := NewTokenHandler()
NewServer := &Server{
// Validate required environment variables
if host == "" || dbPort == "" || username == "" || password == "" || dbName == "" || musicPath == "" || charactersPath == "" {
logging.GetLogger().Fatal("Invalid settings - missing required environment variables")
}
// Create database instance
database, err := db.NewDatabase(host, dbPort, username, password, dbName)
if err != nil {
logging.GetLogger().Fatal("Failed to initialize database", zap.String("error", err.Error()))
}
// Run migrations using the new method
if err := database.RunMigrations(); err != nil {
logging.GetLogger().Fatal("Migration failed", zap.String("error", err.Error()))
}
// Initialize backend package with database pool
backend.InitBackend(database.Pool)
// Initialize token handler with database pool
tokenHandler := NewTokenHandler(database.Pool)
// Create the server instance
appServer := &Server{
port: port,
db: database,
tokenHandler: tokenHandler,
}
// Create the HTTP server
appServer.httpServer = &http.Server{
Addr: fmt.Sprintf(":%d", port),
Handler: appServer.RegisterRoutes(),
IdleTimeout: time.Minute,
ReadTimeout: 10 * time.Second,
WriteTimeout: 30 * time.Second,
}
logger.Info("Starting server",
zap.String("host", host),
zap.String("dbPort", dbPort),
@@ -61,23 +96,21 @@ func NewServer() *http.Server {
zap.String("charactersPath", charactersPath),
)
//conf.SetupDb()
if host == "" || dbPort == "" || username == "" || password == "" || dbName == "" || musicPath == "" || charactersPath == "" {
logging.GetLogger().Fatal("Invalid settings - missing required environment variables")
}
db.Migrate_db(host, dbPort, username, password, dbName)
db.InitDB(host, dbPort, username, password, dbName)
// Declare Server config
server := &http.Server{
Addr: fmt.Sprintf(":%d", NewServer.port),
Handler: NewServer.RegisterRoutes(),
IdleTimeout: time.Minute,
ReadTimeout: 10 * time.Second,
WriteTimeout: 30 * time.Second,
}
return server
return appServer
}
// HTTPServer returns the underlying http.Server for serving HTTP requests.
func (s *Server) HTTPServer() *http.Server {
return s.httpServer
}
// DB returns the database instance for dependency injection.
func (s *Server) DB() *db.Database {
return s.db
}
// NewServer creates a new HTTP server (deprecated, use NewServerInstance instead).
// This function is kept for backward compatibility.
func NewServer() *http.Server {
return NewServerInstance().HTTPServer()
}