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

91 lines
1.5 KiB
Go
Raw Permalink 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"
"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-16 13:20:22 +00:00
const (
SqlGetUser = `
SELECT
user_id,
title,
created_on,
uuid
FROM users
WHERE title=$1;
`
SqlPostUser = `
INSERT INTO users (title, created_on,uuid)
VALUES ($1, $2, $3)
RETURNING user_id`
)
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-11 09:13:41 +00:00
conf := make(map[string]string)
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")
}
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
}