60 lines
1.3 KiB
Go
60 lines
1.3 KiB
Go
package meta
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"net/http"
|
|
"time"
|
|
|
|
"gitea.dwysokinski.me/twhelp/sessions/internal/router/meta/internal/model"
|
|
"github.com/go-chi/chi/v5"
|
|
)
|
|
|
|
// https://datatracker.ietf.org/doc/html/draft-inadarei-api-health-check#section-3.1
|
|
|
|
const (
|
|
checkTimeout = 5 * time.Second
|
|
)
|
|
|
|
type Checker interface {
|
|
Name() string
|
|
Check(ctx context.Context) error
|
|
}
|
|
|
|
func NewRouter(checkers []Checker) *chi.Mux {
|
|
router := chi.NewRouter()
|
|
|
|
router.Get("/livez", func(w http.ResponseWriter, r *http.Request) {
|
|
w.WriteHeader(http.StatusNoContent)
|
|
})
|
|
|
|
router.Get("/readyz", func(w http.ResponseWriter, r *http.Request) {
|
|
resp := model.ReadyResp{
|
|
Status: model.StatusPass,
|
|
Checks: make(model.Checks, len(checkers)),
|
|
}
|
|
|
|
ctx, cancel := context.WithTimeout(r.Context(), checkTimeout)
|
|
defer cancel()
|
|
|
|
for _, ch := range checkers {
|
|
st := model.StatusPass
|
|
if err := ch.Check(ctx); err != nil {
|
|
st = model.StatusFail
|
|
resp.Status = model.StatusFail
|
|
}
|
|
|
|
resp.Checks[ch.Name()] = append(resp.Checks[ch.Name()], model.ComponentStatus{
|
|
Status: st,
|
|
Time: time.Now(),
|
|
})
|
|
}
|
|
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.WriteHeader(resp.Status.ToHTTPStatus())
|
|
_ = json.NewEncoder(w).Encode(resp)
|
|
})
|
|
|
|
return router
|
|
}
|