/
postgres.go
88 lines (71 loc) · 1.66 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package checks
import (
"database/sql"
"fmt"
"time"
_ "github.com/lib/pq"
"github.com/pkg/errors"
)
const POSTGRES Implementation = "postgres"
type postgresCheck struct {
status CheckStatus
lastCheck time.Time
err error
host string
port int
dbName string
user string
pass string
sslMode string
}
func NewPostgresCheck(host string, port int, dbName, user, pass, sslMode string) (CheckInterface, error) {
check := postgresCheck{
status: STARTUP,
lastCheck: time.Unix(0, 0),
err: nil,
host: host,
port: port,
dbName: dbName,
user: user,
pass: pass,
sslMode: sslMode,
}
return &check, nil
}
func (c *postgresCheck) GetImp() Implementation {
return POSTGRES
}
func (c *postgresCheck) GetStatus() CheckStatus {
return c.status
}
func (c *postgresCheck) GetLastCheck() time.Time {
return c.lastCheck
}
func (c *postgresCheck) GetError() error {
return c.err
}
func (c *postgresCheck) HealthCheck() error {
c.status = STARTUP
psqlConnStr := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=%s", c.host, c.port, c.user, c.pass, c.dbName, c.sslMode)
c.status = CHECKING
var conn *sql.DB
conn, c.err = sql.Open("postgres", psqlConnStr)
if c.err != nil {
c.err = errors.Wrap(c.err, "error opening postgres connection")
c.lastCheck = time.Now()
c.status = DONE
return c.err
}
defer conn.Close()
c.err = conn.Ping()
if c.err != nil {
c.err = errors.Wrap(c.err, "error pinging postgres database")
c.lastCheck = time.Now()
c.status = DONE
return c.err
}
c.lastCheck = time.Now()
c.status = DONE
return c.err
}
func (c *postgresCheck) Cleanup() {}