Base Project

This commit is contained in:
Tran Anh Tuan
2026-05-08 14:32:24 +07:00
parent 5a9249c9ea
commit 6a4a96e0ca
74 changed files with 6749 additions and 0 deletions

View File

@@ -0,0 +1,47 @@
package initialization
import (
"context"
"fmt"
"time"
"wm-backend/internal/models"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/rs/zerolog/log"
)
func ConnectPostgreSQL(config *models.Config) (*pgxpool.Pool, error) {
connStr := fmt.Sprintf("postgres://%s:%s@%s:%s/%s?sslmode=disable",
config.Database.Username, config.Database.Password, config.Database.Host, config.Database.Port, config.Database.Name)
var pool *pgxpool.Pool
var err error
maxRetries := 5
for i := range maxRetries {
poolConfig, parseErr := pgxpool.ParseConfig(connStr)
if parseErr != nil {
log.Error().Err(parseErr).Msgf("Failed to parse DB config (attempt %d/%d)", i+1, maxRetries)
time.Sleep(5 * time.Second)
continue
}
pool, err = pgxpool.NewWithConfig(context.Background(), poolConfig)
if err != nil {
log.Error().Err(err).Msgf("Failed to connect to PostgreSQL (attempt %d/%d)", i+1, maxRetries)
time.Sleep(5 * time.Second)
continue
}
err = pool.Ping(context.Background())
if err != nil {
log.Error().Err(err).Msgf("Failed to ping PostgreSQL (attempt %d/%d)", i+1, maxRetries)
time.Sleep(5 * time.Second)
continue
}
log.Info().Msg("Successfully connected to PostgreSQL")
return pool, nil
}
return nil, fmt.Errorf("failed to connect to PostgreSQL after %d attempts: %v", maxRetries, err)
}