added health routes

This commit is contained in:
2026-01-05 14:41:25 +08:00
parent c69a33dfd8
commit 81d3c5a3bd
4 changed files with 90 additions and 2 deletions
+77
View File
@@ -0,0 +1,77 @@
package handlers
import (
"authentication/db"
"authentication/models"
"authentication/redisclient"
"context"
"encoding/json"
"net/http"
"time"
)
func HealthHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(models.HealthResponse{
Status: "ok",
})
}
// 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 := "ready"
statusCode := http.StatusOK
if !allHealthy {
status = "not_ready"
statusCode = http.StatusServiceUnavailable
}
w.WriteHeader(statusCode)
json.NewEncoder(w).Encode(models.HealthResponse{
Status: status,
Services: services,
})
}