Adds health check and test
This commit is contained in:
58
routes/health.go
Normal file
58
routes/health.go
Normal file
@@ -0,0 +1,58 @@
|
||||
package routes
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"gitea.deepak.science/deepak/gogmagog/models"
|
||||
"github.com/go-chi/chi"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
func newHealthRouter(m *models.Model) http.Handler {
|
||||
router := chi.NewRouter()
|
||||
router.Get("/", getHealthFunc(m))
|
||||
return router
|
||||
}
|
||||
|
||||
type healthCheck struct {
|
||||
Name string `json:"name"`
|
||||
Healthy bool `json:"healthy"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
func getHealthFunc(m *models.Model) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
var healths []*healthCheck
|
||||
|
||||
healths = append(healths, dbHealth(m))
|
||||
|
||||
code := http.StatusOK
|
||||
for _, h := range healths {
|
||||
if !h.Healthy {
|
||||
code = http.StatusInternalServerError
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
w.WriteHeader(code)
|
||||
w.Header().Add("Content-Type", "application/json")
|
||||
if err := json.NewEncoder(w).Encode(healths); err != nil {
|
||||
serverError(w, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func dbHealth(m *models.Model) *healthCheck {
|
||||
errMessage := ""
|
||||
health := true
|
||||
name := "Store"
|
||||
err := m.Healthy()
|
||||
if err != nil {
|
||||
errMessage = err.Error()
|
||||
health = false
|
||||
}
|
||||
return &healthCheck{
|
||||
Name: name,
|
||||
Healthy: health,
|
||||
Message: errMessage,
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user