feat: add database configuration for PostgreSQL
- Create config/database.go with GORM PostgreSQL connection - Support environment-based database configuration - Add connection logging and error handling
This commit is contained in:
parent
ee836fa4c8
commit
e40a119bdc
1 changed files with 28 additions and 0 deletions
28
config/database.go
Normal file
28
config/database.go
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
|
||||
"gorm.io/driver/postgres"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func InitDB() *gorm.DB {
|
||||
host := os.Getenv("PG_HOST")
|
||||
port := os.Getenv("PG_PORT")
|
||||
database := os.Getenv("PG_DATABASE")
|
||||
user := os.Getenv("PG_USER")
|
||||
password := os.Getenv("PG_PASSWORD")
|
||||
|
||||
// Try with quoted password
|
||||
dsn := fmt.Sprintf(`host=%s port=%s user=%s password='%s' dbname=%s sslmode=disable`,
|
||||
host, port, user, password, database)
|
||||
|
||||
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
|
||||
if err != nil {
|
||||
log.Fatal("Failed to connect to database:", err)
|
||||
}
|
||||
return db
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue