-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.go
40 lines (32 loc) · 1023 Bytes
/
db.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
package main
import (
"context"
"fmt"
"log"
"os"
"strconv"
"github.com/jackc/pgx/v4/pgxpool"
)
func initDb() *pgxpool.Pool {
// urlExample := "postgres://username:password@localhost:5432/database_name"
pid := os.Getpid()
user := os.Getenv("OPAAPP_DB_USER")
password := os.Getenv("OPAAPP_DB_PASSWORD")
host := os.Getenv("OPAAPP_DB_HOST")
dbport := os.Getenv("OPAAPP_DB_PORT")
dbname := os.Getenv("OPAAPP_DB")
port, err := strconv.ParseInt(dbport, 10, 64)
if err != nil {
log.Printf("pid=%d func=initDb level=error msg=Failed reading DB configuration.", pid)
panic(err)
}
log.Printf("pid=%d func=initDb level=info msg=Initializing Db.", pid)
psqlconn := fmt.Sprintf("postgres://%s:%s@%s:%d/%s", user, password, host, port, dbname)
dbPool, err := pgxpool.Connect(context.Background(), psqlconn)
if err != nil {
log.Printf("pid=%d func=initDb level=error msg=Failed initializing db.", pid)
panic(err)
}
log.Printf("pid=%d func=initDb level=info msg=Initialized Db.", pid)
return dbPool
}