feat: Load database configuration from a centralized config package and add pgAdmin service to Docker Compose

This commit is contained in:
Jean Jacques Avril 2025-03-11 15:11:20 +00:00
parent ec250570a6
commit 2555143c0e
2 changed files with 15 additions and 31 deletions

View File

@ -7,7 +7,6 @@ import (
"net/http"
"os"
"os/signal"
"strconv"
"syscall"
"time"
@ -16,10 +15,9 @@ import (
ginSwagger "github.com/swaggo/gin-swagger"
_ "github.com/timetracker/backend/docs" // This line is important for swag to work
"github.com/timetracker/backend/internal/api/routes"
"github.com/timetracker/backend/internal/config"
"github.com/timetracker/backend/internal/models"
_ "gorm.io/driver/postgres"
"gorm.io/gorm/logger"
// GORM IMPORTS MARKER
)
// @title Time Tracker API
@ -42,37 +40,13 @@ func helloHandler(c *gin.Context) {
}
func main() {
// Get database configuration from environment variables
dbConfig := models.DatabaseConfig{
Host: os.Getenv("DB_HOST"),
Port: 5432, // Default PostgreSQL port
User: os.Getenv("DB_USER"),
Password: os.Getenv("DB_PASSWORD"),
DBName: os.Getenv("DB_NAME"),
SSLMode: os.Getenv("DB_SSLMODE"),
}
// Parse port if provided
if port := os.Getenv("DB_PORT"); port != "" {
if portInt, err := strconv.Atoi(port); err == nil && portInt > 0 {
dbConfig.Port = portInt
}
}
// Validate required configuration
if dbConfig.Host == "" || dbConfig.User == "" || dbConfig.Password == "" || dbConfig.DBName == "" {
log.Fatal("Missing required database configuration. Please set DB_HOST, DB_USER, DB_PASSWORD, and DB_NAME environment variables")
}
// Set log level based on environment
if gin.Mode() == gin.ReleaseMode {
dbConfig.LogLevel = logger.Error // Only log errors in production
} else {
dbConfig.LogLevel = logger.Info // Log more in development
cfg, err := config.LoadConfig()
if err != nil {
log.Fatalf("Failed to load config: %v", err)
}
// Initialize database
if err := models.InitDB(dbConfig); err != nil {
if err := models.InitDB(cfg.Database); err != nil {
log.Fatalf("Error initializing database: %v", err)
}
defer func() {

View File

@ -11,6 +11,16 @@ services:
POSTGRES_DB: timetracker
volumes:
- db_data:/var/lib/postgresql/data
pgadmin:
image: dpage/pgadmin4
container_name: pgadmin
environment:
PGADMIN_DEFAULT_EMAIL: admin@example.com
PGADMIN_DEFAULT_PASSWORD: admin
ports:
- "8081:80"
depends_on:
- db
volumes:
db_data: