link-go/database/database.go
2021-03-13 01:43:08 +06:00

47 lines
967 B
Go

package database
import (
"context"
"errors"
"fmt"
"github.com/jackc/pgx/v4/pgxpool"
"github.com/knadh/koanf"
)
func Pool(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
}