40 lines
777 B
Go
40 lines
777 B
Go
|
package main
|
||
|
|
||
|
import (
|
||
|
"fmt"
|
||
|
"github.com/jmoiron/sqlx"
|
||
|
_ "github.com/lib/pq"
|
||
|
"os"
|
||
|
)
|
||
|
|
||
|
func envMustExist(env string) string {
|
||
|
if value, exists := os.LookupEnv(env); !exists {
|
||
|
panic(fmt.Sprintf("env variable '%s' not defined", env))
|
||
|
} else {
|
||
|
return value
|
||
|
}
|
||
|
}
|
||
|
|
||
|
func connectToDb() (*sqlx.DB, error) {
|
||
|
host := envMustExist("PSQL_HOST")
|
||
|
port := envMustExist("PSQL_PORT")
|
||
|
user := envMustExist("PSQL_USER")
|
||
|
password := envMustExist("PSQL_PASSWORD")
|
||
|
dbname := envMustExist("PSQL_DB")
|
||
|
|
||
|
psqlInfo := fmt.Sprintf("host=%s port=%s user=%s password=%s dbname=%s sslmode=disable",
|
||
|
host, port, user, password, dbname)
|
||
|
|
||
|
db, err := sqlx.Open("postgres", psqlInfo)
|
||
|
if err != nil {
|
||
|
return nil, err
|
||
|
}
|
||
|
|
||
|
err = db.Ping()
|
||
|
if err != nil {
|
||
|
return nil, err
|
||
|
}
|
||
|
|
||
|
return db, nil
|
||
|
}
|