POC-golang-postgres-docker/internal/app/db.go

75 lines
1.2 KiB
Go
Raw Normal View History

2020-09-14 13:16:47 +00:00
package app
2020-09-11 09:13:41 +00:00
import (
"database/sql"
"fmt"
"github.com/joho/godotenv"
"log"
"os"
2020-09-11 09:13:41 +00:00
)
const (
dbhost = "dbhost"
dbport = "dbport"
dbuser = "dbuser"
dbpass = "dbpass"
dbname = "dbname"
2020-09-11 09:13:41 +00:00
)
2020-09-14 13:16:47 +00:00
var Db *sql.DB
2020-09-11 09:13:41 +00:00
2020-09-14 13:16:47 +00:00
func InitDb() {
2020-09-11 09:13:41 +00:00
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)
2020-09-14 13:16:47 +00:00
Db, err = sql.Open("postgres", psqlInfo)
2020-09-11 09:13:41 +00:00
if err != nil {
panic(err)
}
2020-09-14 13:16:47 +00:00
err = Db.Ping()
2020-09-11 09:13:41 +00:00
if err != nil {
panic(err)
}
fmt.Println("Successfully connected!")
}
2020-09-14 13:16:47 +00:00
func CloseDB() {
Db.Close()
}
// return the value of the key
func goDotEnvVariable(key string) string {
// load .env file
2020-09-15 11:15:26 +00:00
pwd, _ := os.Getwd()
err := godotenv.Load(pwd + "/configs/web.env")
if err != nil {
log.Fatalf(err.Error())
}
return os.Getenv(key)
}
2020-09-11 09:13:41 +00:00
func dbConfig() map[string]string {
2020-09-11 09:13:41 +00:00
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
2020-09-11 09:13:41 +00:00
return conf
}