forked from mtusi2026/mtusi2026lab2
Implement lab2 messenger API with PostgreSQL Redis and Docker
This commit is contained in:
@@ -0,0 +1,56 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
func NewPostgresPool(
|
||||
ctx context.Context,
|
||||
databaseURL string,
|
||||
) (*pgxpool.Pool, error) {
|
||||
config, err := pgxpool.ParseConfig(databaseURL)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf(
|
||||
"invalid database config: %w",
|
||||
err,
|
||||
)
|
||||
}
|
||||
|
||||
config.MaxConns = 10
|
||||
config.MinConns = 1
|
||||
config.MaxConnLifetime = 30 * time.Minute
|
||||
config.MaxConnIdleTime = 5 * time.Minute
|
||||
config.HealthCheckPeriod = time.Minute
|
||||
config.ConnConfig.ConnectTimeout = 5 * time.Second
|
||||
|
||||
connectCtx, cancel := context.WithTimeout(
|
||||
ctx,
|
||||
10*time.Second,
|
||||
)
|
||||
defer cancel()
|
||||
|
||||
pool, err := pgxpool.NewWithConfig(
|
||||
connectCtx,
|
||||
config,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf(
|
||||
"create postgres pool: %w",
|
||||
err,
|
||||
)
|
||||
}
|
||||
|
||||
if err := pool.Ping(connectCtx); err != nil {
|
||||
pool.Close()
|
||||
return nil, fmt.Errorf(
|
||||
"postgres unavailable: %w",
|
||||
err,
|
||||
)
|
||||
}
|
||||
|
||||
return pool, nil
|
||||
}
|
||||
Reference in New Issue
Block a user