forked from mtusi2026/mtusi2026lab3
40 lines
1.1 KiB
Go
40 lines
1.1 KiB
Go
package httpapi
|
|
|
|
import (
|
|
"context"
|
|
"net/http"
|
|
"sync/atomic"
|
|
"time"
|
|
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
"github.com/redis/go-redis/v9"
|
|
)
|
|
|
|
func handleHealthLive(w http.ResponseWriter, r *http.Request) {
|
|
writeJSON(w, http.StatusOK, newRequestID(), map[string]string{"status": "ok"})
|
|
}
|
|
|
|
func handleHealthReady(pool *pgxpool.Pool, rdb *redis.Client, draining *atomic.Bool) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
requestID := newRequestID()
|
|
if draining.Load() {
|
|
writeError(w, http.StatusServiceUnavailable, requestID, codeUnavailable, "shutting down")
|
|
return
|
|
}
|
|
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
|
|
defer cancel()
|
|
|
|
if err := pool.Ping(ctx); err != nil {
|
|
writeError(w, http.StatusServiceUnavailable, requestID, codeUnavailable, "database unavailable")
|
|
return
|
|
}
|
|
if rdb != nil {
|
|
if err := rdb.Ping(ctx).Err(); err != nil {
|
|
writeError(w, http.StatusServiceUnavailable, requestID, codeUnavailable, "session store unavailable")
|
|
return
|
|
}
|
|
}
|
|
writeJSON(w, http.StatusOK, requestID, map[string]string{"status": "ok"})
|
|
}
|
|
}
|