forked from mtusi2026/mtusi2026lab6
55 lines
1.5 KiB
Go
55 lines
1.5 KiB
Go
package http
|
|
|
|
import (
|
|
"context"
|
|
"net/http"
|
|
"sync/atomic"
|
|
"time"
|
|
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
"github.com/redis/go-redis/v9"
|
|
|
|
"github.com/charawein/mtusi2026lab6/internal/service"
|
|
"github.com/charawein/mtusi2026lab6/internal/transport/httputil"
|
|
)
|
|
|
|
type HealthHandler struct {
|
|
pool *pgxpool.Pool
|
|
redis *redis.Client
|
|
draining *atomic.Bool
|
|
}
|
|
|
|
func NewHealthHandler(pool *pgxpool.Pool, redisClient *redis.Client, draining *atomic.Bool) *HealthHandler {
|
|
return &HealthHandler{pool: pool, redis: redisClient, draining: draining}
|
|
}
|
|
|
|
// Live проверяет только жизнь процесса.
|
|
func (h *HealthHandler) Live(w http.ResponseWriter, r *http.Request) {
|
|
httputil.WriteJSON(w, r, http.StatusOK, healthResponse{Status: "ok"})
|
|
}
|
|
|
|
// Ready проверяет доступность PostgreSQL и Redis.
|
|
// После SIGTERM возвращает 503, чтобы LB исключил реплику до закрытия listener.
|
|
func (h *HealthHandler) Ready(w http.ResponseWriter, r *http.Request) {
|
|
if h.draining.Load() {
|
|
httputil.WriteError(w, r, service.ErrUnavailable)
|
|
return
|
|
}
|
|
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
|
|
defer cancel()
|
|
|
|
if err := h.pool.Ping(ctx); err != nil {
|
|
httputil.WriteError(w, r, service.ErrUnavailable)
|
|
return
|
|
}
|
|
if err := h.redis.Ping(ctx).Err(); err != nil {
|
|
httputil.WriteError(w, r, service.ErrUnavailable)
|
|
return
|
|
}
|
|
httputil.WriteJSON(w, r, http.StatusOK, healthResponse{Status: "ok"})
|
|
}
|
|
|
|
type healthResponse struct {
|
|
Status string `json:"status"`
|
|
}
|