59 lines
1.1 KiB
Go
59 lines
1.1 KiB
Go
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,
|
|
}
|
|
}
|