From 870b4ccb6c753397ba41e7f398ff09687ae6acaf Mon Sep 17 00:00:00 2001 From: Markus Wiegand Date: Sun, 24 Jan 2021 06:05:12 +0100 Subject: [PATCH] improve health check error handling --- controller/health.go | 4 ++-- model/api/health.go | 35 ++++++++++++++++------------------- 2 files changed, 18 insertions(+), 21 deletions(-) diff --git a/controller/health.go b/controller/health.go index 6f3f672..de5775f 100644 --- a/controller/health.go +++ b/controller/health.go @@ -11,9 +11,9 @@ import ( // HealthGET handles a GET request on the health endpoint func HealthGET(w http.ResponseWriter, _ *http.Request, _ httprouter.Params) { - h, err := api.GetHealth() + h := api.GetHealth() - if err != nil || !h.OK { + if !h.OK { view.RenderJSON(h, http.StatusInternalServerError, w) } else { view.RenderJSON(h, http.StatusOK, w) diff --git a/model/api/health.go b/model/api/health.go index 535cdb4..cde244a 100644 --- a/model/api/health.go +++ b/model/api/health.go @@ -6,6 +6,7 @@ import ( "os" "time" + "github.com/google/logger" "github.com/tarkov-database/rest-api/core/database" ) @@ -50,42 +51,38 @@ type Service struct { } // GetHealth performs a self-check and returns the result -func GetHealth() (*Health, error) { - var err error - var ok = true - +func GetHealth() *Health { svc := &Service{} - svc.Database, err = getDatabaseStatus() - if err != nil { - return nil, err + health := &Health{ + OK: true, + Service: svc, } + svc.Database = getDatabaseStatus() if svc.Database != OK { - ok = false - } - - health := &Health{ - OK: ok, - Service: svc, + health.OK = false } - return health, nil + return health } -func getDatabaseStatus() (Status, error) { +func getDatabaseStatus() Status { ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() start := time.Now() if err := database.Ping(ctx); err != nil { - return Failure, err + logger.Errorf("Error while checking database connection: %s", err) + return Failure } - if time.Since(start) > latencyThreshold { - return Warning, nil + latency := time.Since(start) + if latency > latencyThreshold { + logger.Warningf("Database latency exceeds threshold with %s", latency) + return Warning } - return OK, nil + return OK }