-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase.go
More file actions
54 lines (46 loc) · 1.06 KB
/
database.go
File metadata and controls
54 lines (46 loc) · 1.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package main
import (
"context"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/joho/godotenv"
"github.com/redis/go-redis/v9"
"log/slog"
"os"
"sync"
)
type DatabaseClient struct {
db *pgxpool.Pool
redisClient *redis.Client
dbMut *sync.Mutex
redisMut *sync.Mutex
}
func NewDatabaseClient() *DatabaseClient {
dotEnvErr := godotenv.Load()
if dotEnvErr != nil {
slog.Error("Error loading .env file, exiting")
os.Exit(1)
}
// Connect to database
connStr := os.Getenv("DATABASE_URL")
slog.Debug(connStr)
sqlDB, dbErr := pgxpool.New(context.Background(), connStr)
if dbErr != nil {
slog.Error(dbErr.Error())
slog.Error("Error connecting to database, exiting")
os.Exit(1)
}
// Connect to Redis
redisAddr := os.Getenv("REDIS_URL")
opt, redisErr := redis.ParseURL(redisAddr)
if redisErr != nil {
slog.Error("Error connecting to Redis, exiting")
os.Exit(1)
}
redisClient := redis.NewClient(opt)
return &DatabaseClient{
db: sqlDB,
redisClient: redisClient,
dbMut: &sync.Mutex{},
redisMut: &sync.Mutex{},
}
}