Files
mtusi2026lab2_fork/backend/internal/httpapi/handler/health.go
T

43 lines
907 B
Go

package handler
import (
"context"
"net/http"
"time"
"github.com/gin-gonic/gin"
"high-loud-apps-labs/internal/domain"
"high-loud-apps-labs/internal/httpapi/dto"
)
type HealthCheck func(ctx context.Context) error
type HealthHandler struct {
checks []HealthCheck
}
func NewHealthHandler(checks ...HealthCheck) *HealthHandler {
return &HealthHandler{checks: checks}
}
func (h *HealthHandler) Live(c *gin.Context) {
c.JSON(http.StatusOK, dto.HealthResponse{Status: "ok"})
}
func (h *HealthHandler) Ready(c *gin.Context) {
ctx, cancel := context.WithTimeout(c.Request.Context(), 2*time.Second)
defer cancel()
for _, check := range h.checks {
if check == nil {
continue
}
if err := check(ctx); err != nil {
respondError(c, &domain.UnavailableError{Reason: "зависимость недоступна"})
return
}
}
c.JSON(http.StatusOK, dto.HealthResponse{Status: "ok"})
}