43 lines
928 B
Go
43 lines
928 B
Go
package database
|
|
|
|
import (
|
|
"log"
|
|
|
|
"github.com/joho/godotenv"
|
|
"github.com/spf13/viper"
|
|
"gorm.io/driver/mysql"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
var shared_db_connection *gorm.DB
|
|
|
|
func initDB() *gorm.DB {
|
|
// load .env into environment (so viper can read them)
|
|
if err := godotenv.Load(); err != nil {
|
|
log.Println(".env not found or could not be loaded; proceeding with existing environment variables")
|
|
}
|
|
|
|
viper.AutomaticEnv() // read from environment
|
|
|
|
sql_dsn := viper.GetString("SQL_DSN")
|
|
|
|
if sql_dsn == "" {
|
|
log.Fatal("SQL_DSN must be set in .env or environment")
|
|
}
|
|
|
|
db, err := gorm.Open(mysql.Open(sql_dsn), &gorm.Config{})
|
|
if err != nil {
|
|
log.Fatalf("failed to connect to MySQL Server: %v", err)
|
|
}
|
|
|
|
log.Println("connected to MySQL Server")
|
|
return db
|
|
}
|
|
|
|
func Init() *gorm.DB {
|
|
if shared_db_connection == nil {
|
|
shared_db_connection = initDB()
|
|
}
|
|
return shared_db_connection
|
|
}
|