Spaces:
Runtime error
Runtime error
Download util/database.go from alberdjuniawan/anput-api: direct link, hf CLI and curl.
- Browser
- Download file 930 Bytes
-
https://huggingface.co/spaces/alberdjuniawan/anput-api/resolve/main/util/database.go
- Command line
-
hf download hf://spaces/alberdjuniawan/anput-api/util/database.go
-
curl -L -o database.go https://huggingface.co/spaces/alberdjuniawan/anput-api/resolve/main/util/database.go
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() | |
| } | |