77 lines
1.8 KiB
Go
77 lines
1.8 KiB
Go
package handlers
|
|
|
|
import (
|
|
"authentication/db"
|
|
"authentication/helper"
|
|
"authentication/models"
|
|
"authentication/redisclient"
|
|
"context"
|
|
"net/http"
|
|
"time"
|
|
)
|
|
|
|
func HealthHandler(w http.ResponseWriter, r *http.Request) {
|
|
response := models.HealthResponse{
|
|
Status: "AuthN Capy!",
|
|
}
|
|
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 := "Capy!"
|
|
statusCode := http.StatusOK
|
|
if !allHealthy {
|
|
status = "not Capy!"
|
|
statusCode = http.StatusServiceUnavailable
|
|
}
|
|
|
|
w.WriteHeader(statusCode)
|
|
helper.RespondWithJSON(w, statusCode, models.HealthResponse{
|
|
Status: status,
|
|
Services: services,
|
|
})
|
|
}
|