This repository has been archived by the owner on Feb 6, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
postgres.go
72 lines (54 loc) · 1.51 KB
/
postgres.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
package main
import (
"fmt"
"net/http"
"strconv"
"github.com/oslokommune/okctl-hello/pkg/postgres"
"github.com/sirupsen/logrus"
)
func enablePostgres(server *http.ServeMux, logger *logrus.Logger, rawDSN string) error {
dsn := postgres.ParseDSN(rawDSN)
if err := dsn.Validate(); err != nil {
return fmt.Errorf("validating DSN: %w", err)
}
pgClient := postgres.Client{DSN: dsn}
dbErrorFields := logrus.Fields{
"database-host": pgClient.DSN.URI,
"database-port": pgClient.DSN.Port,
"database-user": pgClient.DSN.Username,
}
server.HandleFunc("/postgres/write", func(w http.ResponseWriter, r *http.Request) {
err := pgClient.Open()
if err != nil {
logger.WithFields(dbErrorFields).Errorf("opening database: %s", err.Error())
return
}
defer func() {
_ = pgClient.Close()
}()
err = pgClient.Write()
if err != nil {
logger.WithFields(dbErrorFields).Errorf("writing to database: %s", err.Error())
return
}
w.WriteHeader(http.StatusOK)
})
server.HandleFunc("/postgres/read", func(w http.ResponseWriter, r *http.Request) {
err := pgClient.Open()
if err != nil {
logger.WithFields(dbErrorFields).Errorf("opening database: %s", err.Error())
return
}
defer func() {
_ = pgClient.Close()
}()
currentHits, err := pgClient.Read()
if err != nil {
logger.WithFields(dbErrorFields).Errorf("reading from database: %s", err.Error())
return
}
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(fmt.Sprintf("hits: %s", strconv.Itoa(currentHits))))
})
return nil
}