2020-09-14 13:16:47 +00:00
|
|
|
package app
|
2020-09-11 09:13:41 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"database/sql"
|
|
|
|
"fmt"
|
2020-09-15 09:53:57 +00:00
|
|
|
"os"
|
2020-09-11 09:13:41 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
2020-09-15 09:53:57 +00:00
|
|
|
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()
|
|
|
|
}
|
|
|
|
|
2020-09-11 09:13:41 +00:00
|
|
|
func dbConfig() map[string]string {
|
2020-09-15 09:53:57 +00:00
|
|
|
|
2020-09-11 09:13:41 +00:00
|
|
|
conf := make(map[string]string)
|
2020-09-15 09:53:57 +00:00
|
|
|
|
2020-09-15 12:59:37 +00:00
|
|
|
host, ok := os.LookupEnv(dbhost)
|
|
|
|
if !ok {
|
|
|
|
panic("DBHOST environment variable required but not set")
|
|
|
|
}
|
|
|
|
port, ok := os.LookupEnv(dbport)
|
|
|
|
if !ok {
|
|
|
|
panic("DBPORT environment variable required but not set")
|
|
|
|
}
|
|
|
|
user, ok := os.LookupEnv(dbuser)
|
|
|
|
if !ok {
|
|
|
|
panic("DBUSER environment variable required but not set")
|
|
|
|
}
|
|
|
|
password, ok := os.LookupEnv(dbpass)
|
|
|
|
if !ok {
|
|
|
|
panic("DBPASS environment variable required but not set")
|
|
|
|
}
|
|
|
|
name, ok := os.LookupEnv(dbname)
|
|
|
|
if !ok {
|
|
|
|
panic("DBNAME environment variable required but not set")
|
|
|
|
}
|
2020-09-15 09:53:57 +00:00
|
|
|
|
|
|
|
conf[dbhost] = host
|
|
|
|
conf[dbport] = port
|
|
|
|
conf[dbuser] = user
|
2020-09-15 12:59:37 +00:00
|
|
|
conf[dbpass] = password
|
|
|
|
conf[dbname] = name
|
2020-09-11 09:13:41 +00:00
|
|
|
return conf
|
|
|
|
}
|