move db connection process to seperate file
This commit is contained in:
45
golang/internal/model/database/connect.go
Normal file
45
golang/internal/model/database/connect.go
Normal file
@@ -0,0 +1,45 @@
|
||||
package database
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
)
|
||||
|
||||
// Will try to connect to the database defined by the env variables. If the
|
||||
// connection fails a error will be returned. Ensure that the returned sql.DB
|
||||
// object is closed after use.
|
||||
func DbConnection() (*sql.DB, error) {
|
||||
// collect environement variables
|
||||
dbPass := os.Getenv("DB_PASS")
|
||||
if dbPass == "" {
|
||||
return nil, errors.New("empty env. variable DB_PASS")
|
||||
}
|
||||
dbHost := os.Getenv("DB_HOST")
|
||||
if dbHost == "" {
|
||||
return nil, errors.New("empty env. variable DB_HOST")
|
||||
}
|
||||
dbPort := os.Getenv("DB_PORT")
|
||||
if dbPort == "" {
|
||||
dbPort = "5432"
|
||||
}
|
||||
dbUser := os.Getenv("DB_USER")
|
||||
if dbUser == "" {
|
||||
dbUser = "postgres"
|
||||
}
|
||||
dbName := os.Getenv("DB_NAME")
|
||||
|
||||
// connect to database
|
||||
databaseURL := fmt.Sprintf("user=%s password=%s dbname=%s host=%s port=%s sslmode=disable",
|
||||
dbUser, dbPass, dbName, dbHost, dbPort)
|
||||
db, err := sql.Open("postgres", databaseURL)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err = db.Ping(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return db, nil
|
||||
}
|
||||
Reference in New Issue
Block a user