initial commit, adding SQL connection and a simple testing on main
This commit is contained in:
42
app/libs/database/db.go
Normal file
42
app/libs/database/db.go
Normal file
@@ -0,0 +1,42 @@
|
||||
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
|
||||
}
|
||||
Reference in New Issue
Block a user