30 lines
531 B
Go
30 lines
531 B
Go
package db
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"time"
|
|
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
)
|
|
|
|
type DB struct {
|
|
Pool *pgxpool.Pool
|
|
}
|
|
|
|
func ConnectPostgres(url string) (*DB, error) {
|
|
pool, err := pgxpool.New(context.Background(), url)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to create DB: %w", err)
|
|
}
|
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
|
defer cancel()
|
|
|
|
if err := pool.Ping(ctx); err != nil {
|
|
return nil, fmt.Errorf("failed to connect to DB: %w", err)
|
|
}
|
|
|
|
return &DB{Pool: pool}, nil
|
|
}
|