feat: prefer DATABASE_URL format for db connection, fallback to individual params
This commit is contained in:
parent
2111e7e32d
commit
924255fdfb
2 changed files with 46 additions and 33 deletions
|
|
@ -1,12 +1,15 @@
|
||||||
# Environment variables for GoHorse Jobs Backend
|
# Environment variables for GoHorse Jobs Backend
|
||||||
|
|
||||||
# Database Configuration
|
# Database Configuration (preferred: use DATABASE_URL)
|
||||||
DB_HOST=localhost
|
DATABASE_URL=postgresql://user:password@localhost:5432/gohorsejobs?sslmode=require
|
||||||
DB_PORT=5432
|
|
||||||
DB_USER=postgres
|
# Alternative: Individual params (used if DATABASE_URL not set)
|
||||||
DB_PASSWORD=yourpassword
|
# DB_HOST=localhost
|
||||||
DB_NAME=gohorsejobs
|
# DB_PORT=5432
|
||||||
DB_SSLMODE=disable
|
# DB_USER=postgres
|
||||||
|
# DB_PASSWORD=yourpassword
|
||||||
|
# DB_NAME=gohorsejobs
|
||||||
|
# DB_SSLMODE=require
|
||||||
|
|
||||||
# S3/Object Storage Configuration (Civo S3-compatible)
|
# S3/Object Storage Configuration (Civo S3-compatible)
|
||||||
AWS_REGION=nyc1
|
AWS_REGION=nyc1
|
||||||
|
|
|
||||||
|
|
@ -14,9 +14,17 @@ var DB *sql.DB
|
||||||
|
|
||||||
func InitDB() {
|
func InitDB() {
|
||||||
var err error
|
var err error
|
||||||
|
var connStr string
|
||||||
|
|
||||||
|
// Prefer DATABASE_URL if set (standard format)
|
||||||
|
if dbURL := os.Getenv("DATABASE_URL"); dbURL != "" {
|
||||||
|
connStr = dbURL
|
||||||
|
log.Println("Using DATABASE_URL for connection")
|
||||||
|
} else {
|
||||||
|
// Fallback to individual params for backward compatibility
|
||||||
host := os.Getenv("DB_HOST")
|
host := os.Getenv("DB_HOST")
|
||||||
if host == "" {
|
if host == "" {
|
||||||
log.Fatal("DB_HOST environment variable not set")
|
log.Fatal("DATABASE_URL or DB_HOST environment variable not set")
|
||||||
}
|
}
|
||||||
user := os.Getenv("DB_USER")
|
user := os.Getenv("DB_USER")
|
||||||
if user == "" {
|
if user == "" {
|
||||||
|
|
@ -40,8 +48,10 @@ func InitDB() {
|
||||||
sslmode = "require" // Default to require for production security
|
sslmode = "require" // Default to require for production security
|
||||||
}
|
}
|
||||||
|
|
||||||
connStr := fmt.Sprintf("host=%s port=%s user=%s password=%s dbname=%s sslmode=%s",
|
connStr = fmt.Sprintf("host=%s port=%s user=%s password=%s dbname=%s sslmode=%s",
|
||||||
host, port, user, password, dbname, sslmode)
|
host, port, user, password, dbname, sslmode)
|
||||||
|
log.Println("Using individual DB_* params for connection")
|
||||||
|
}
|
||||||
|
|
||||||
DB, err = sql.Open("postgres", connStr)
|
DB, err = sql.Open("postgres", connStr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue