summaryrefslogtreecommitdiff
path: root/app/controllers/health/controller.go
blob: 99ff4cdd256f807122fc9675a5f1158f77e4c71a (plain)
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
package health

import (
	"context"
	"net/http"
	"time"

	"github.com/xlgmokha/x/pkg/serde"
	"gitlab.com/gitlab-org/software-supply-chain-security/authorization/sparkled/app/db"
)

type Controller struct {
	dbConnection *db.Connection
}

func New(dbConnection *db.Connection) *Controller {
	return &Controller{
		dbConnection: dbConnection,
	}
}

func (c *Controller) MountTo(mux *http.ServeMux) {
	mux.Handle("GET /-/health", http.HandlerFunc(c.Health))
	mux.Handle("GET /-/health/database", http.HandlerFunc(c.Database))
}

func (c *Controller) Health(w http.ResponseWriter, r *http.Request) {
	w.WriteHeader(http.StatusOK)
	serde.ToHTTP(w, r, map[string]string{"status": "ok"})
}

func (c *Controller) Database(w http.ResponseWriter, r *http.Request) {
	ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
	defer cancel()

	if c.dbConnection.IsHealthy(ctx) {
		w.WriteHeader(http.StatusOK)
		serde.ToHTTP(w, r, map[string]string{"database": "ok"})
	} else {
		w.WriteHeader(http.StatusServiceUnavailable)
		serde.ToHTTP(w, r, map[string]string{"database": "unavailable"})
	}
}