Add full shop application: Go backend, PostgreSQL, Docker, Caddy and admin panel.
This commit is contained in:
@@ -0,0 +1,51 @@
|
||||
package database
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
func Connect(ctx context.Context) (*pgxpool.Pool, error) {
|
||||
dsn := fmt.Sprintf(
|
||||
"postgres://%s:%s@%s:%s/%s?sslmode=disable",
|
||||
getEnv("DB_USER", "shop"),
|
||||
getEnv("DB_PASSWORD", "shop_secret"),
|
||||
getEnv("DB_HOST", "localhost"),
|
||||
getEnv("DB_PORT", "5432"),
|
||||
getEnv("DB_NAME", "shop"),
|
||||
)
|
||||
|
||||
cfg, err := pgxpool.ParseConfig(dsn)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse config: %w", err)
|
||||
}
|
||||
|
||||
cfg.MaxConns = 10
|
||||
cfg.MinConns = 2
|
||||
cfg.MaxConnLifetime = time.Hour
|
||||
|
||||
pool, err := pgxpool.NewWithConfig(ctx, cfg)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("connect: %w", err)
|
||||
}
|
||||
|
||||
for i := 0; i < 30; i++ {
|
||||
if err := pool.Ping(ctx); err == nil {
|
||||
return pool, nil
|
||||
}
|
||||
time.Sleep(time.Second)
|
||||
}
|
||||
|
||||
return nil, fmt.Errorf("database not ready after 30s")
|
||||
}
|
||||
|
||||
func getEnv(key, fallback string) string {
|
||||
if v := os.Getenv(key); v != "" {
|
||||
return v
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
Reference in New Issue
Block a user