-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdata_sources.go
82 lines (65 loc) · 1.93 KB
/
data_sources.go
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package main
import (
"context"
"fmt"
"log"
"os"
"github.com/go-redis/redis/v8"
"github.com/jmoiron/sqlx"
_ "github.com/lib/pq"
)
type dataSources struct {
DB *sqlx.DB
RedisClient *redis.Client
}
// InitDS establishes connections to fields in dataSources
func initDS() (*dataSources, error) {
log.Printf("Initializing data sources\n")
// load env variables - we could pass these in,
// but this is sort of just a top-level (main package)
// helper function, so I'll just read them in here
pgHost := os.Getenv("PG_HOST")
pgPort := os.Getenv("PG_PORT")
pgUser := os.Getenv("PG_USER")
pgPassword := os.Getenv("PG_PASSWORD")
pgDB := os.Getenv("PG_DB")
pgSSL := os.Getenv("PG_SSL")
pgConnString := fmt.Sprintf("host=%s port=%s user=%s password=%s dbname=%s sslmode=%s", pgHost, pgPort, pgUser, pgPassword, pgDB, pgSSL)
log.Printf("Connecting to Postgresql\n")
db, err := sqlx.Open("postgres", pgConnString)
if err != nil {
return nil, fmt.Errorf("error opening db: %w", err)
}
// Verify database connection is working
if err := db.Ping(); err != nil {
return nil, fmt.Errorf("error connecting to db: %w", err)
}
// Initialize redis connection
redisHost := os.Getenv("REDIS_HOST")
redisPort := os.Getenv("REDIS_PORT")
log.Printf("Connecting to Redis\n")
rdb := redis.NewClient(&redis.Options{
Addr: fmt.Sprintf("%s:%s", redisHost, redisPort),
Password: "",
DB: 0,
})
// verify redis connection
_, err = rdb.Ping(context.Background()).Result()
if err != nil {
return nil, fmt.Errorf("error connecting to redis: %w", err)
}
return &dataSources{
DB: db,
RedisClient: rdb,
}, nil
}
// close to be used in graceful server shutdown
func (d *dataSources) close() error {
if err := d.DB.Close(); err != nil {
return fmt.Errorf("error closing Postgresql: %w", err)
}
if err := d.RedisClient.Close(); err != nil {
return fmt.Errorf("error closing Redis Client: %w", err)
}
return nil
}