74 lines
1.2 KiB
Go
74 lines
1.2 KiB
Go
package app
|
|
|
|
import (
|
|
"database/sql"
|
|
"fmt"
|
|
"github.com/joho/godotenv"
|
|
"log"
|
|
"os"
|
|
)
|
|
|
|
const (
|
|
dbhost = "dbhost"
|
|
dbport = "dbport"
|
|
dbuser = "dbuser"
|
|
dbpass = "dbpass"
|
|
dbname = "dbname"
|
|
)
|
|
|
|
var Db *sql.DB
|
|
|
|
func InitDb() {
|
|
config := dbConfig()
|
|
var err error
|
|
psqlInfo := fmt.Sprintf("postgres://%v:%v@%v:%v/%v?sslmode=disable",
|
|
config[dbuser], config[dbpass],
|
|
config[dbhost], config[dbport], config[dbname])
|
|
|
|
fmt.Println(psqlInfo)
|
|
Db, err = sql.Open("postgres", psqlInfo)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
err = Db.Ping()
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
fmt.Println("Successfully connected!")
|
|
}
|
|
|
|
func CloseDB() {
|
|
Db.Close()
|
|
}
|
|
|
|
// return the value of the key
|
|
func goDotEnvVariable(key string) string {
|
|
|
|
// load .env file
|
|
err := godotenv.Load("/go/src/app/configs/web.env")
|
|
|
|
if err != nil {
|
|
log.Fatalf(err.Error())
|
|
}
|
|
|
|
return os.Getenv(key)
|
|
}
|
|
|
|
func dbConfig() map[string]string {
|
|
|
|
conf := make(map[string]string)
|
|
|
|
user := goDotEnvVariable(dbuser)
|
|
host := goDotEnvVariable(dbhost)
|
|
port := goDotEnvVariable(dbport)
|
|
pass := goDotEnvVariable(dbpass)
|
|
databaseNname := goDotEnvVariable(dbname)
|
|
|
|
conf[dbhost] = host
|
|
conf[dbport] = port
|
|
conf[dbuser] = user
|
|
conf[dbpass] = pass
|
|
conf[dbname] = databaseNname
|
|
return conf
|
|
}
|