anput-api / util /database.go
alberdjuniawan's picture
update conns to be stateless
d88d7c4
Raw History Blame Contribute Delete
930 Bytes
package util
import (
"context"
"fmt"
"log"
"os"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
)
type DBClient struct {
Pool *pgxpool.Pool
}
func NewDBClient(ctx context.Context) (*DBClient, error) {
connStr := os.Getenv("DATABASE_URL")
if connStr == "" {
return nil, fmt.Errorf("DATABASE_URL environment variable is not set")
}
config, err := pgxpool.ParseConfig(connStr)
if err != nil {
return nil, fmt.Errorf("failed to parse config: %w", err)
}
config.ConnConfig.DefaultQueryExecMode = pgx.QueryExecModeSimpleProtocol
pool, err := pgxpool.NewWithConfig(ctx, config)
if err != nil {
return nil, fmt.Errorf("failed to connect to db: %w", err)
}
if err := pool.Ping(ctx); err != nil {
return nil, fmt.Errorf("failed to ping db: %w", err)
}
log.Println("Connected to PostgreSQL successfully!")
return &DBClient{Pool: pool}, nil
}
func (c *DBClient) Close() {
c.Pool.Close()
}