mirror of
https://github.com/Mezeporta/Erupe.git
synced 2026-03-22 07:32:32 +01:00
feat(api): add /health endpoint with Docker healthchecks
Allow Docker to distinguish a running container from one actually serving traffic by adding a /health endpoint that pings the database. Returns 200 when healthy, 503 when the DB connection is lost. Add HEALTHCHECK to Dockerfile and healthcheck config to the server service in docker-compose.yml. Also add start_period to the existing db healthcheck for consistency.
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"encoding/xml"
|
||||
@@ -443,3 +444,30 @@ func (s *APIServer) ScreenShot(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
writeResult("200")
|
||||
}
|
||||
|
||||
// Health handles GET /health, returning the server's health status.
|
||||
// It pings the database to verify connectivity.
|
||||
func (s *APIServer) Health(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
if s.db == nil {
|
||||
w.WriteHeader(http.StatusServiceUnavailable)
|
||||
_ = json.NewEncoder(w).Encode(map[string]string{
|
||||
"status": "unhealthy",
|
||||
"error": "database not configured",
|
||||
})
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 3*time.Second)
|
||||
defer cancel()
|
||||
if err := s.db.PingContext(ctx); err != nil {
|
||||
w.WriteHeader(http.StatusServiceUnavailable)
|
||||
_ = json.NewEncoder(w).Encode(map[string]string{
|
||||
"status": "unhealthy",
|
||||
"error": err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(map[string]string{
|
||||
"status": "ok",
|
||||
})
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user