package health import ( "context" "net/http" "strings" "time" "github.com/gogf/gf/v2/frame/g" "github.com/gogf/gf/v2/net/ghttp" "hotgo/internal/library/queue" ) type response struct { Status string `json:"status"` Checks map[string]string `json:"checks"` } // Serve exposes an unauthenticated dependency health endpoint for container probes. func Serve(r *ghttp.Request) { if r.Method != http.MethodGet && r.Method != http.MethodHead { r.Response.Header().Set("Allow", http.MethodGet+", "+http.MethodHead) r.Response.WriteStatusExit(http.StatusMethodNotAllowed, "method not allowed") return } ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second) defer cancel() checks := map[string]string{} statusCode := http.StatusOK if err := g.DB().Ctx(ctx).Raw("SELECT 1").Scan(new(int)); err != nil { checks["mysql"] = err.Error() statusCode = http.StatusServiceUnavailable } else { checks["mysql"] = "ok" } if _, err := g.Redis().Do(ctx, "PING"); err != nil { checks["redis"] = err.Error() statusCode = http.StatusServiceUnavailable } else { checks["redis"] = "ok" } if strings.EqualFold(strings.TrimSpace(g.Cfg().MustGet(ctx, "queue.driver").String()), "kafka") { if err := queue.KafkaHealthCheck(ctx); err != nil { checks["kafka"] = err.Error() statusCode = http.StatusServiceUnavailable } else { checks["kafka"] = "ok" } } else { checks["kafka"] = "disabled" } body := response{Status: "ok", Checks: checks} if statusCode != http.StatusOK { body.Status = "error" } r.Response.Header().Set("Content-Type", "application/json; charset=utf-8") r.Response.WriteHeader(statusCode) if r.Method != http.MethodHead { r.Response.WriteJsonExit(body) return } r.Exit() }