47 lines
970 B
Go
47 lines
970 B
Go
package database
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"github.com/jackc/pgx/v4/pgxpool"
|
|
"github.com/knadh/koanf"
|
|
)
|
|
|
|
func NewPool(config *koanf.Koanf) *pgxpool.Pool {
|
|
connStr, err := getConnectionString(config)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
pool, err := pgxpool.Connect(context.Background(), connStr)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
return pool
|
|
}
|
|
|
|
func getConnectionString(config *koanf.Koanf) (string, error) {
|
|
username := config.String("db.username")
|
|
if username == "" {
|
|
return "", errors.New("database username is missing")
|
|
}
|
|
|
|
password := config.String("db.password")
|
|
if password == "" {
|
|
return "", errors.New("database password is missing")
|
|
}
|
|
|
|
name := config.String("db.name")
|
|
if name == "" {
|
|
return "", errors.New("database name is missing")
|
|
}
|
|
|
|
host := config.String("db.host")
|
|
if name == "" {
|
|
return "", errors.New("database host is missing")
|
|
}
|
|
|
|
return fmt.Sprintf("postgresql://%s:%s@%s/%s", username, password, host, name), nil
|
|
}
|