61 lines
1.2 KiB
Go
61 lines
1.2 KiB
Go
package handler
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"log/slog"
|
|
"net/http"
|
|
"time"
|
|
|
|
"mtusi2026-messenger/internal/dto"
|
|
"mtusi2026-messenger/internal/httpx"
|
|
)
|
|
|
|
const readyPingTimeout = 2 * time.Second
|
|
|
|
type Pinger interface {
|
|
Ping(ctx context.Context) error
|
|
}
|
|
|
|
type HealthHandler struct {
|
|
log *slog.Logger
|
|
db Pinger
|
|
}
|
|
|
|
func NewHealthHandler(log *slog.Logger, db Pinger) *HealthHandler {
|
|
return &HealthHandler{log: log, db: db}
|
|
}
|
|
|
|
func (h *HealthHandler) Live(w http.ResponseWriter, r *http.Request) {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.WriteHeader(http.StatusOK)
|
|
|
|
_ = json.NewEncoder(w).Encode(dto.HealthResponse{
|
|
Status: "ok",
|
|
})
|
|
}
|
|
|
|
func (h *HealthHandler) Ready(w http.ResponseWriter, r *http.Request) {
|
|
ctx, cancel := context.WithTimeout(r.Context(), readyPingTimeout)
|
|
defer cancel()
|
|
|
|
if err := h.db.Ping(ctx); err != nil {
|
|
h.log.ErrorContext(r.Context(), "readiness check failed", "error", err)
|
|
httpx.WriteError(
|
|
w,
|
|
http.StatusServiceUnavailable,
|
|
dto.ErrorCodeUnavailable,
|
|
"service unavailable",
|
|
w.Header().Get("X-Request-Id"),
|
|
)
|
|
return
|
|
}
|
|
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.WriteHeader(http.StatusOK)
|
|
|
|
_ = json.NewEncoder(w).Encode(dto.HealthResponse{
|
|
Status: "ok",
|
|
})
|
|
}
|