87 lines
2.2 KiB
Go
87 lines
2.2 KiB
Go
package handlers
|
|
|
|
import (
|
|
"authorization/db"
|
|
"authorization/helper"
|
|
"authorization/models"
|
|
"authorization/redisclient"
|
|
"context"
|
|
"encoding/json"
|
|
"net/http"
|
|
"time"
|
|
)
|
|
|
|
// HealthHandler provides a basic liveness check
|
|
// @Summary Health check endpoint
|
|
// @Description Returns service health status for load balancer health checks
|
|
// @Tags health
|
|
// @Produce json
|
|
// @Success 200 {object} HealthResponse
|
|
// @Router /health [get]
|
|
func HealthHandler(w http.ResponseWriter, r *http.Request) {
|
|
response := models.HealthResponse{
|
|
Status: "ok",
|
|
}
|
|
helper.RespondWithJSON(w, http.StatusOK, response)
|
|
}
|
|
|
|
// ReadyHandler checks if the service is ready to handle requests
|
|
// @Summary Readiness check endpoint
|
|
// @Description Returns readiness status including database and Redis connectivity
|
|
// @Tags health
|
|
// @Produce json
|
|
// @Success 200 {object} HealthResponse
|
|
// @Failure 503 {object} HealthResponse
|
|
// @Router /ready [get]
|
|
func ReadyHandler(w http.ResponseWriter, r *http.Request) {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
|
|
services := make(map[string]string)
|
|
allHealthy := true
|
|
|
|
// Check database
|
|
if db.DB != nil {
|
|
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
|
|
defer cancel()
|
|
if err := db.DB.PingContext(ctx); err != nil {
|
|
services["database"] = "unhealthy"
|
|
allHealthy = false
|
|
} else {
|
|
services["database"] = "healthy"
|
|
}
|
|
} else {
|
|
services["database"] = "not_initialized"
|
|
allHealthy = false
|
|
}
|
|
|
|
// Check Redis
|
|
if redisclient.RDB != nil {
|
|
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
|
|
defer cancel()
|
|
if _, err := redisclient.RDB.Ping(ctx).Result(); err != nil {
|
|
services["redis"] = "unhealthy"
|
|
allHealthy = false
|
|
} else {
|
|
services["redis"] = "healthy"
|
|
}
|
|
} else {
|
|
services["redis"] = "not_initialized"
|
|
allHealthy = false
|
|
}
|
|
|
|
status := "AuthZ Capy!"
|
|
statusCode := http.StatusOK
|
|
if !allHealthy {
|
|
status = "AuthZ not Capy!"
|
|
statusCode = http.StatusServiceUnavailable
|
|
}
|
|
|
|
w.WriteHeader(statusCode)
|
|
if err := json.NewEncoder(w).Encode(models.HealthResponse{
|
|
Status: status,
|
|
Services: services,
|
|
}); err != nil {
|
|
helper.LogError(err, "Error encoding health response")
|
|
}
|
|
}
|