forked from mtusi2026/mtusi2026lab4
58 lines
1.2 KiB
Go
58 lines
1.2 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"os"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
)
|
|
|
|
func readSecret(envKey, fileKey string) (string, error) {
|
|
if v := os.Getenv(envKey); v != "" {
|
|
return strings.TrimSpace(v), nil
|
|
}
|
|
path := os.Getenv(fileKey)
|
|
if path == "" {
|
|
return "", fmt.Errorf("%s or %s required", envKey, fileKey)
|
|
}
|
|
b, err := os.ReadFile(path)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
return strings.TrimSpace(string(b)), nil
|
|
}
|
|
|
|
func openDB(ctx context.Context) (*pgxpool.Pool, error) {
|
|
dsn, err := readSecret("DATABASE_URL", "DATABASE_URL_FILE")
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
cfg, err := pgxpool.ParseConfig(dsn)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
cfg.MaxConns = 10
|
|
cfg.MinConns = 2
|
|
cfg.MaxConnLifetime = 5 * time.Minute
|
|
cfg.ConnConfig.ConnectTimeout = 3 * time.Second
|
|
|
|
pool, err := pgxpool.NewWithConfig(ctx, cfg)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
pingCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
|
defer cancel()
|
|
if err := pool.Ping(pingCtx); err != nil {
|
|
pool.Close()
|
|
return nil, err
|
|
}
|
|
return pool, nil
|
|
}
|
|
|
|
func dbCtx(parent context.Context) (context.Context, context.CancelFunc) {
|
|
return context.WithTimeout(parent, 3*time.Second)
|
|
}
|