diff options
Diffstat (limited to 'app/controllers/health')
| -rw-r--r-- | app/controllers/health/controller.go | 43 |
1 files changed, 43 insertions, 0 deletions
diff --git a/app/controllers/health/controller.go b/app/controllers/health/controller.go new file mode 100644 index 0000000..99ff4cd --- /dev/null +++ b/app/controllers/health/controller.go @@ -0,0 +1,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"}) + } +} |
