feat(db): connect to PostgreSQL and check it in /health/ready

This commit is contained in:
kk10
2026-10-03 12:36:05 +03:00
parent 60fad0fca7
commit 492e0be15c
6 changed files with 138 additions and 4 deletions
+43 -1
View File
@@ -1,13 +1,55 @@
package handler
import (
"context"
"encoding/json"
"log/slog"
"net/http"
"time"
"mtusi2026-messenger/internal/dto"
)
func Health(w http.ResponseWriter, r *http.Request) {
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)
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)