Skip to content

Commit

Permalink
improve health check error handling
Browse files Browse the repository at this point in the history
  • Loading branch information
morphy2k committed Jan 24, 2021
1 parent fc511b6 commit 870b4cc
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 21 deletions.
4 changes: 2 additions & 2 deletions controller/health.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
35 changes: 16 additions & 19 deletions model/api/health.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"os"
"time"

"github.com/google/logger"
"github.com/tarkov-database/rest-api/core/database"
)

Expand Down Expand Up @@ -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
}

0 comments on commit 870b4cc

Please sign in to comment.