forked from hellofresh/health-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
check.go
56 lines (48 loc) · 1.42 KB
/
check.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
package mysql
import (
"context"
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql" // import mysql driver
)
// Config is the MySQL checker configuration settings container.
type Config struct {
// DSN is the MySQL instance connection DSN. Required.
DSN string
}
// New creates new MySQL health check that verifies the following:
// - connection establishing
// - doing the ping command
// - selecting mysql version
func New(config Config) func(ctx context.Context) error {
return func(ctx context.Context) (checkErr error) {
db, err := sql.Open("mysql", config.DSN)
if err != nil {
checkErr = fmt.Errorf("MySQL health check failed on connect: %w", err)
return
}
defer func() {
// override checkErr only if there were no other errors
if err = db.Close(); err != nil && checkErr == nil {
checkErr = fmt.Errorf("MySQL health check failed on connection closing: %w", err)
}
}()
err = db.PingContext(ctx)
if err != nil {
checkErr = fmt.Errorf("MySQL health check failed on ping: %w", err)
return
}
rows, err := db.QueryContext(ctx, `SELECT VERSION()`)
if err != nil {
checkErr = fmt.Errorf("MySQL health check failed on select: %w", err)
return
}
defer func() {
// override checkErr only if there were no other errors
if err = rows.Close(); err != nil && checkErr == nil {
checkErr = fmt.Errorf("MySQL health check failed on rows closing: %w", err)
}
}()
return
}
}