### Basic Health Checker Setup Source: https://context7.com/alexliesenfeld/health/llms.txt This section demonstrates how to set up a basic health checker with a database ping check and configurable timeouts and cache durations. ```APIDOC ## GET /health ### Description Provides a health status endpoint for the application. ### Method GET ### Endpoint /health ### Parameters None ### Request Example None ### Response #### Success Response (200) - **status** (string) - Indicates the overall health status of the application ('up' or 'down'). - **details** (object) - Contains the health status of individual components. - **component_name** (object) - Status details for a specific component. - **status** (string) - Health status of the component ('up' or 'down'). - **timestamp** (string) - ISO 8601 timestamp of the last check. - **error** (string, optional) - Error message if the component is down. #### Response Example (Success) ```json { "status": "up", "details": { "database": { "status": "up", "timestamp": "2025-12-04T10:30:00Z" } } } ``` #### Response Example (Failure) ```json { "status": "down", "details": { "database": { "status": "down", "timestamp": "2025-12-04T10:30:00Z", "error": "connection refused" } } } ``` ``` -------------------------------- ### Integrate etherlabsio/healthcheck Disk Space Check Source: https://github.com/alexliesenfeld/health/blob/main/README.md This code example shows how to incorporate a disk space check from the 'etherlabsio/healthcheck' library. It uses the 'checkers.DiskSpace' function to monitor a specified path and threshold, and then assigns its 'Check' method to the health system's check configuration. ```go import "github.com/etherlabsio/healthcheck/v2/checkers" ... health.WithCheck(health.Check{ Name: "database", Check: checkers.DiskSpace("/var/log", 90).Check, }) ``` -------------------------------- ### Integrate heptiolabs/healthcheck HTTP GET Check Source: https://github.com/alexliesenfeld/health/blob/main/README.md This snippet illustrates integrating an HTTP GET check using the 'heptiolabs/healthcheck' library. It defines a custom check function that leverages 'healthcheck.HTTPGetCheck' and passes the URL and a timeout derived from the context's deadline. This check is then registered with the health system. ```go import "github.com/heptiolabs/healthcheck" ... health.WithCheck(health.Check{ Name: "google", Check: func(ctx context.Context) error { deadline, _ := ctx.Deadline() timeout := time.Since(deadline) return healthcheck.HTTPGetCheck("https://www.google.com", timeout)() }, }), ``` -------------------------------- ### Control Manual Checker Lifecycle in Go Source: https://context7.com/alexliesenfeld/health/llms.txt This Go code shows how to manually control the lifecycle of the health checker, disabling its automatic start. It demonstrates starting the checker explicitly using `checker.Start()` and stopping it using `checker.Stop()`. This provides fine-grained control over when health checks are performed, suitable for specific application startup or shutdown sequences. ```go checker := health.NewChecker( health.WithDisabledAutostart(), health.WithPeriodicCheck(10*time.Second, 0, health.Check{ Name: "service", Check: serviceCheck, }), ) // Checker is not started yet log.Printf("Checker started: %v", checker.IsStarted()) // false // Start manually when ready checker.Start() log.Printf("Checker started: %v", checker.IsStarted()) // true // Check running periodic checks log.Printf("Periodic checks: %d", checker.GetRunningPeriodicCheckCount()) // 1 // Stop when shutting down checker.Stop() log.Printf("Checker started: %v", checker.IsStarted()) // false ``` -------------------------------- ### Integrate InVisionApp/go-health HTTP Check Source: https://github.com/alexliesenfeld/health/blob/main/README.md This example shows how to use an HTTP checker from the 'InVisionApp/go-health' library. It first creates an HTTP checker instance with a specified URL configuration and then wraps its status check within a function compatible with the current health system's 'Check' interface. ```go import "github.com/InVisionApp/go-health/checkers" ... // Create check as usual (no error checking for brevity) googleURL, err := url.Parse("https://www.google.com") check, err := checkers.NewHTTP(&checkers.HTTPConfig{ URL: googleURL, }) ... // Add the check in the Checker configuration. health.WithCheck(health.Check{ Name: "google", Check: func(_ context.Context) error { _, err := check.Status() return err }, }) ``` -------------------------------- ### Integrate Health Checks with Kubernetes Probes in Go and YAML Source: https://context7.com/alexliesenfeld/health/llms.txt This example demonstrates integrating health checks with Kubernetes probes. It includes a Go program that sets up a health check handler accessible at `/healthz` and a Kubernetes deployment YAML configuration that uses this endpoint for liveness and readiness probes. This ensures Kubernetes can effectively monitor and manage the application's health. ```go func main() { checker := health.NewChecker( health.WithPeriodicCheck(15*time.Second, 0, health.Check{ Name: "database", Check: db.PingContext, }), ) http.Handle("/healthz", health.NewHandler(checker)) http.ListenAndServe(":8080", nil) } ``` ```yaml # kubernetes/deployment.yaml apiVersion: v1 kind: Pod metadata: name: myapp spec: containers: - name: myapp image: myapp:latest ports: - containerPort: 8080 livenessProbe: httpGet: path: /healthz port: 8080 initialDelaySeconds: 10 periodSeconds: 15 timeoutSeconds: 5 failureThreshold: 3 readinessProbe: httpGet: path: /healthz port: 8080 initialDelaySeconds: 5 periodSeconds: 10 timeoutSeconds: 3 failureThreshold: 2 ``` -------------------------------- ### GET /health Source: https://github.com/alexliesenfeld/health/blob/main/README.md The health check endpoint returns the aggregated health status of the application's components. It supports both synchronous and asynchronous checks and utilizes caching for efficiency. ```APIDOC ## GET /health ### Description Retrieves the current health status of the application. This endpoint aggregates results from configured synchronous and periodic (asynchronous) checks. ### Method GET ### Endpoint /health ### Parameters None ### Request Example None ### Response #### Success Response (200 OK) Returns a JSON object detailing the overall status and status of individual checks. - **status** (string) - Overall health status of the application ('up' or 'down'). - **details** (object) - An object containing the status of each configured check. - **check_name** (object) - Details for a specific check. - **status** (string) - Status of the individual check ('up' or 'down'). - **timestamp** (string) - The time the check was last performed (ISO 8601 format). - **error** (string, optional) - The error message if the check failed. #### Response Example ```json { "status": "down", "details": { "database": { "status": "up", "timestamp": "2021-07-01T08:05:14.603364Z" }, "search": { "status": "down", "timestamp": "2021-07-01T08:05:08.522685Z", "error": "this makes the check fail" } } } ``` #### Error Response (503 Service Unavailable) Returned if the overall application status is 'down'. The response body will be the same as the success response, but with an HTTP status code of 503. ``` -------------------------------- ### Integrate External Go Health Check Libraries Source: https://context7.com/alexliesenfeld/health/llms.txt Demonstrates how to integrate health checks from external Go libraries (hellofresh/health-go, etherlabsio/healthcheck, heptiolabs/healthcheck) into the health checker. This allows leveraging existing check implementations, such as HTTP checks, disk space checks, and custom HTTP GET checks, by adapting their output to the health checker's expected interface. ```go // hellofresh/health-go import httpCheck "github.com/hellofresh/health-go/v4/checks/http" checker := health.NewChecker( health.WithCheck(health.Check{ Name: "google", Check: httpCheck.New(httpCheck.Config{ URL: "https://www.google.com", }), }), ) // etherlabsio/healthcheck import "github.com/etherlabsio/healthcheck/v2/checkers" checker := health.NewChecker( health.WithCheck(health.Check{ Name: "disk", Check: checkers.DiskSpace("/var/log", 90).Check, }), ) // heptiolabs/healthcheck import "github.com/heptiolabs/healthcheck" checker := health.NewChecker( health.WithCheck(health.Check{ Name: "api", Check: func(ctx context.Context) error { deadline, _ := ctx.Deadline() timeout := time.Until(deadline) return healthcheck.HTTPGetCheck("https://api.example.com", timeout)() }, }), ) ``` -------------------------------- ### Apply Middleware to Health Check Requests Source: https://context7.com/alexliesenfeld/health/llms.txt Enhance health check handling by applying middleware to intercept and modify requests and responses. This Go example demonstrates using middleware for basic logging, enforcing authentication, and conditionally showing full details based on a query parameter. ```go import ( "github.com/alexliesenfeld/health" "github.com/alexliesenfeld/health/middleware" ) checker := health.NewChecker( health.WithCheck(health.Check{ Name: "database", Check: db.PingContext, }), ) handler := health.NewHandler(checker, health.WithMiddleware( // Log all health check requests middleware.BasicLogger(), // Require authentication to see details middleware.BasicAuth("admin", "secret"), // Show details only if ?full query param present middleware.FullDetailsOnQueryParam("full"), ), ) http.Handle("/health", handler) // Request without auth: returns only aggregated status // curl http://localhost:3000/health // {"status": "up"} // Request with auth: returns full details // curl -u admin:secret http://localhost:3000/health // {"status": "up", "details": {"database": {"status": "up", ...}}} // Request with query param: returns full details // curl http://localhost:3000/health?full // {"status": "up", "details": {"database": {"status": "up", ...}}} ``` -------------------------------- ### Example JSON Health Response Source: https://github.com/alexliesenfeld/health/blob/main/README.md This JSON output represents the health status of the application when the 'search' component is down. It shows the overall status and details for each registered check, including their status, timestamp, and any errors. This format is returned by the /health HTTP endpoint. ```json { "status": "down", "details": { "database": { "status": "up", "timestamp": "2021-07-01T08:05:14.603364Z" }, "search": { "status": "down", "timestamp": "2021-07-01T08:05:08.522685Z", "error": "this makes the check fail" } } } ``` -------------------------------- ### Implement Synchronous Health Check in Go Source: https://context7.com/alexliesenfeld/health/llms.txt Shows how to implement a synchronous health check for a Redis service. The check executes on each HTTP request to the health endpoint. Includes example success and failure JSON responses. ```go checker := health.NewChecker( health.WithCheck(health.Check{ Name: "redis", Timeout: 2 * time.Second, Check: func(ctx context.Context) error { // Perform health check - return nil if healthy, error if not conn, err := redis.DialContext(ctx, "tcp", "localhost:6379") if err != nil { return err } defer conn.Close() _, err = conn.Do("PING") return err }, }), ) // Response on success (HTTP 200): // { // "status": "up", // "details": { // "redis": { // "status": "up", // "timestamp": "2025-12-04T10:30:00Z" // } // } // } // Response on failure (HTTP 503): // { // "status": "down", // "details": { // "redis": { // "status": "down", // "timestamp": "2025-12-04T10:30:00Z", // "error": "connection refused" // } // } // } ``` -------------------------------- ### Using Interceptors for Component Check Function Interception in Go Source: https://github.com/alexliesenfeld/health/blob/main/README.md Utilize interceptor functions to hook into individual component check function calls. This is beneficial for reusable cross-functional code that requires access to check state information, such as logging. Dependencies include the 'context' package. An example is the BasicLogger interceptor. ```Go import ( "context" "github.com/alexliesenfeld/health/interceptors" ) func setupHealthInterceptors() { // Example: Using BasicLogger interceptor var loggerInterceptor health.InterceptorFunc loggerInterceptor = interceptors.BasicLogger(nil) // Pass a logger implementation if needed // Interceptors can be applied when configuring individual checks: // health.Check{ // Name: "myComponent", // Check: myCheckFunc, // Interceptors: []health.InterceptorFunc{loggerInterceptor}, // } } ``` -------------------------------- ### Synchronous Health Checks Source: https://context7.com/alexliesenfeld/health/llms.txt Synchronous checks are executed on every HTTP request to the health endpoint. This example shows a Redis ping check. ```APIDOC ## POST /health (Synchronous Check Example) ### Description This illustrates a synchronous health check for a Redis service. The check runs every time the /health endpoint is hit. ### Method GET ### Endpoint /health ### Parameters None ### Request Example None ### Response #### Success Response (200) - **status** (string) - Overall health status ('up'). - **details** (object) - Health status of components. - **redis** (object) - **status** (string) - Component status ('up'). - **timestamp** (string) - ISO 8601 timestamp of the check. #### Response Example (Success) ```json { "status": "up", "details": { "redis": { "status": "up", "timestamp": "2025-12-04T10:30:00Z" } } } ``` #### Response Example (Failure) ```json { "status": "down", "details": { "redis": { "status": "down", "timestamp": "2025-12-04T10:30:00Z", "error": "connection refused" } } } ``` ``` -------------------------------- ### Periodic (Asynchronous) Health Checks Source: https://context7.com/alexliesenfeld/health/llms.txt Periodic checks run in the background on a schedule, providing instant responses using cached results. This example configures an external API check. ```APIDOC ## GET /health (Periodic Check Behavior) ### Description Demonstrates periodic health checks where the check runs in the background at a set interval. HTTP requests to the health endpoint return immediately with the last cached result. ### Method GET ### Endpoint /health ### Parameters None ### Request Example None ### Response #### Success Response (200) - **status** (string) - Overall health status ('up'). - **details** (object) - Health status of components. - **external-api** (object) - **status** (string) - Component status ('up'). - **timestamp** (string) - ISO 8601 timestamp of the last check. #### Response Example (Cached Success) ```json { "status": "up", "details": { "external-api": { "status": "up", "timestamp": "2025-12-04T10:35:00Z" } } } ``` #### Response Example (Cached Failure) ```json { "status": "down", "details": { "external-api": { "status": "down", "timestamp": "2025-12-04T10:35:00Z", "error": "API returned status 500" } } } ``` ``` -------------------------------- ### Implement Tracing Interceptor for Health Checks in Go Source: https://context7.com/alexliesenfeld/health/llms.txt This Go code defines a custom interceptor for health check functions that integrates with a tracing system. It starts a new span for each health check, logs the check's status and contiguous failures as attributes, and then ends the span. This provides visibility into the performance and state of individual health checks. ```go import "github.com/alexliesenfeld/health/interceptors" func TracingInterceptor() health.Interceptor { return func(next health.InterceptorFunc) health.InterceptorFunc { return func(ctx context.Context, name string, state health.CheckState) health.CheckState { span := trace.StartSpan(ctx, "health_check_"+name) defer span.End() result := next(ctx, name, state) span.SetAttribute("status", string(result.Status)) span.SetAttribute("contiguous_fails", result.ContiguousFails) return result } } } checker := health.NewChecker( // Global interceptor for all checks health.WithInterceptors( interceptors.BasicLogger(), TracingInterceptor(), ), health.WithCheck(health.Check{ Name: "database", Check: db.PingContext, // Check-specific interceptor Interceptors: []health.Interceptor{ interceptors.BasicLogger(), }, }), ) ``` -------------------------------- ### Go Health Check Implementation Source: https://github.com/alexliesenfeld/health/blob/main/README.md This Go code sets up a health checker with database and periodic checks. It configures caching, timeouts, and a status listener, then exposes the health status via an HTTP handler. Dependencies include 'context', 'database/sql', 'fmt', 'github.com/alexliesenfeld/health', 'github.com/mattn/go-sqlite3', 'log', 'net/http', and 'time'. ```go package main import ( "context" "database/sql" "fmt" "github.com/alexliesenfeld/health" _ "github.com/mattn/go-sqlite3" "log" "net/http" "time" ) // This is a very simple example that shows the basic features of this library. func main() { db, _ := sql.Open("sqlite3", "simple.sqlite") defer db.Close() // Create a new Checker. checker := health.NewChecker( // Set the time-to-live for our cache to 1 second (default). health.WithCacheDuration(1*time.Second), // Configure a global timeout that will be applied to all checks. health.WithTimeout(10*time.Second), // A check configuration to see if our database connection is up. // The check function will be executed for each HTTP request. health.WithCheck(health.Check{ Name: "database", // A unique check name. Timeout: 2 * time.Second, // A check specific timeout. Check: db.PingContext, }), // The following check will be executed periodically every 15 seconds // started with an initial delay of 3 seconds. The check function will NOT // be executed for each HTTP request. health.WithPeriodicCheck(15*time.Second, 3*time.Second, health.Check{ Name: "search", // The check function checks the health of a component. If an error is // returned, the component is considered unavailable (or "down"). // The context contains a deadline according to the configured timeouts. Check: func(ctx context.Context) error { return fmt.Errorf("this makes the check fail") }, }), // Set a status listener that will be invoked when the health status changes. // More powerful hooks are also available (see docs). health.WithStatusListener(func(ctx context.Context, state health.CheckerState) { log.Println(fmt.Sprintf("health status changed to %s", state.Status)) }), )) // Create a new health check http.Handler that returns the health status // serialized as a JSON string. You can pass pass further configuration // options to NewHandler to modify default configuration. http.Handle("/health", health.NewHandler(checker)) log.Fatalln(http.ListenAndServe(":3000", nil)) } ``` -------------------------------- ### Integrate hellofresh/health-go HTTP Check Source: https://github.com/alexliesenfeld/health/blob/main/README.md This snippet demonstrates how to integrate an HTTP check from the 'hellofresh/health-go' library into the current health check system. It utilizes the 'httpCheck.New' function with a configuration specifying the target URL. The check is then added to the health system using 'health.WithCheck'. ```go import httpCheck "github.com/hellofresh/health-go/v4/checks/http" ... health.WithCheck(health.Check{ Name: "google", Check: httpCheck.New(httpCheck.Config{ URL: "https://www.google.com", }), }), ``` -------------------------------- ### Create Basic Health Checker in Go Source: https://context7.com/alexliesenfeld/health/llms.txt Demonstrates setting up a basic health checker with a database ping as a dependency. It configures timeouts and cache durations for the health checks. The checker is then registered as an HTTP handler. ```go package main import ( "context" "database/sql" "github.com/alexliesenfeld/health" _ "github.com/mattn/go-sqlite3" "log" "net/http" "time" ) func main() { db, _ := sql.Open("sqlite3", "app.sqlite") defer db.Close() checker := health.NewChecker( health.WithTimeout(10*time.Second), health.WithCacheDuration(1*time.Second), health.WithCheck(health.Check{ Name: "database", Timeout: 2 * time.Second, Check: db.PingContext, }), ) http.Handle("/health", health.NewHandler(checker)) log.Fatal(http.ListenAndServe(":3000", nil)) } ``` -------------------------------- ### Listening to Health Status Changes in Go Source: https://github.com/alexliesenfeld/health/blob/main/README.md Configure listener functions to react to changes in overall or component-specific health statuses. These listeners are invoked when a status changes, allowing for actions like logging or metric adjustments. Dependencies include the 'context' and 'time' packages. ```Go import ( "context" "log" "time" "github.com/alexliesenfeld/health" ) func setupHealthListeners(ctx context.Context) { // Listener for individual component status changes health.WithPeriodicCheck(5*time.Second, 0, health.Check{ Name: "search", Check: myCheckFunc, // Assume myCheckFunc is defined elsewhere StatusListener: func (ctx context.Context, name string, state health.CheckState) { log.Printf("status of component '%s' changed to %s", name, state.Status) }, }), // Listener for overall system health status changes health.WithStatusListener(func (ctx context.Context, state health.CheckerState) { log.Printf("overall system health status changed to %s", state.Status) }), } // Placeholder for the actual check function func myCheckFunc(ctx context.Context) error { // Implement your health check logic here return nil } ``` -------------------------------- ### Combine Synchronous and Periodic Health Checks in Go Source: https://context7.com/alexliesenfeld/health/llms.txt Demonstrates combining fast synchronous checks (like memory usage) with potentially expensive periodic checks (like disk space) in Go. This approach optimizes performance by using cached results for slower checks while ensuring quick responses for critical ones. ```go checker := health.NewChecker( health.WithTimeout(10*time.Second), health.WithCacheDuration(1*time.Second), // Fast synchronous check health.WithCheck(health.Check{ Name: "memory", Timeout: 100 * time.Millisecond, Check: func(ctx context.Context) error { var m runtime.MemStats runtime.ReadMemStats(&m) if m.Alloc > 1024*1024*1024 { // 1GB return fmt.Errorf("memory usage too high: %d bytes", m.Alloc) } return nil }, }), // Expensive periodic check health.WithPeriodicCheck(30*time.Second, 0, health.Check{ Name: "disk-space", Check: func(ctx context.Context) error { var stat syscall.Statfs_t syscall.Statfs("/var/log", &stat) available := stat.Bavail * uint64(stat.Bsize) if available < 1024*1024*100 { // 100MB return fmt.Errorf("low disk space: %d bytes available", available) } return nil }, }), ) ``` -------------------------------- ### Configure Periodic (Asynchronous) Health Check in Go Source: https://context7.com/alexliesenfeld/health/llms.txt Illustrates setting up a periodic health check for an external API. The check runs in the background at a fixed interval, allowing the health endpoint to respond instantly with cached results. Specifies the check frequency and initial delay. ```go checker := health.NewChecker( // Check runs every 15 seconds with 3 second initial delay health.WithPeriodicCheck(15*time.Second, 3*time.Second, health.Check{ Name: "external-api", Check: func(ctx context.Context) error { resp, err := http.Get("https://api.example.com/status") if err != nil { return err } defer resp.Body.Close() if resp.StatusCode != 200 { return fmt.Errorf("API returned status %d", resp.StatusCode) } return nil }, Timeout: 5 * time.Second, }), ) // HTTP requests return immediately with last cached result // Check function executes in background every 15 seconds ``` -------------------------------- ### Using Middleware for Health Check Interception in Go Source: https://github.com/alexliesenfeld/health/blob/main/README.md Employ middleware functions to intercept all calls to Checker.Check, allowing pre-processing before a check executes and post-processing of results before an HTTP response. Useful for adding tracing, logging, or modifying results. Dependencies include the 'context' package. Available middleware includes BasicAuth, CustomAuth, FullDetailsOnQueryParam, and BasicLogger. ```Go import ( "context" "github.com/alexliesenfeld/health/middleware" ) func setupHealthMiddleware() { // Example: Using BasicLogger middleware var loggerMiddleware health.MiddlewareFunc loggerMiddleware = middleware.BasicLogger(nil) // Pass a logger implementation if needed // Example: Using FullDetailsOnQueryParam middleware var detailsMiddleware health.MiddlewareFunc detailsMiddleware = middleware.FullDetailsOnQueryParam("healthcheck") // These middleware functions can be combined or applied as needed when configuring the health checker. // For instance, when creating a new health checker: // checker := health.NewChecker( // health.WithMiddleware(loggerMiddleware, detailsMiddleware), // // ... other health check configurations // ) } ``` -------------------------------- ### Implement Health Status Listeners Source: https://context7.com/alexliesenfeld/health/llms.txt React to health status changes by implementing status listeners. These can be used for global system status changes or component-specific events, enabling actions like logging, sending metrics, or triggering automated remediation such as alerts. ```go checker := health.NewChecker( // Global status listener for overall system status health.WithStatusListener(func(ctx context.Context, state health.CheckerState) { log.Printf("System health changed to: %s", state.Status) // Send metric to monitoring system metrics.Gauge("health.status", state.Status) }), // Component-specific listener health.WithCheck(health.Check{ Name: "database", Check: db.PingContext, StatusListener: func(ctx context.Context, name string, state health.CheckState) { log.Printf("Component %s status: %s (fails: %d)", name, state.Status, state.ContiguousFails) if state.Status == health.StatusDown { // Trigger alert alerting.Send("Database health check failed") } }, }), ) ``` -------------------------------- ### Create Custom Rate Limiting Middleware in Go Source: https://context7.com/alexliesenfeld/health/llms.txt This Go middleware limits the rate at which health checks are executed. It uses a token bucket limiter to allow a specified number of requests per second. If the limit is exceeded, it returns an 'unknown' status without running the actual checks, preventing excessive load. ```go func RateLimitMiddleware() health.Middleware { limiter := rate.NewLimiter(rate.Every(time.Second), 10) return func(next health.MiddlewareFunc) health.MiddlewareFunc { return func(r *http.Request) health.CheckerResult { if !limiter.Allow() { // Return cached result without executing checks return health.CheckerResult{ Status: health.StatusUnknown, } } return next(r) } } } handler := health.NewHandler(checker, health.WithMiddleware(RateLimitMiddleware()), ) ``` -------------------------------- ### Configure Custom HTTP Status Codes for Health States in Go Source: https://context7.com/alexliesenfeld/health/llms.txt This Go code demonstrates how to customize the HTTP status codes returned by the health check handler. It shows how to set specific codes for 'up' and 'down' states, overriding the defaults. This is useful for integrating with systems that expect particular HTTP responses for different service health conditions. ```go handler := health.NewHandler(checker, health.WithStatusCodeUp(http.StatusOK), // 200 (default) health.WithStatusCodeDown(http.StatusServiceUnavailable), // 503 (default) ) // Alternative: use custom codes handler := health.NewHandler(checker, health.WithStatusCodeUp(http.StatusOK), // 200 health.WithStatusCodeDown(http.StatusInternalServerError), // 500 ) http.Handle("/health", handler) // When all checks pass: HTTP 200 // When any check fails: HTTP 503 (or configured code) ``` -------------------------------- ### Include Service Information in Health Responses Source: https://context7.com/alexliesenfeld/health/llms.txt Enrich health check responses by including static and dynamic metadata. Static information like version and environment can be provided directly, while dynamic information such as uptime and goroutine count can be computed at check time using `WithInfoFunc`. ```go checker := health.NewChecker( // Static information health.WithInfo(map[string]interface{}{ "version": "v1.2.3", "environment": "production", "region": "us-east-1", }), // Dynamic information computed at check time health.WithInfoFunc(func(info map[string]interface{}) { info["uptime_seconds"] = time.Since(startTime).Seconds() info["goroutines"] = runtime.NumGoroutine() }), health.WithCheck(health.Check{ Name: "api", Check: apiCheck, }), ) // Response includes info section: // { // "status": "up", // "info": { // "version": "v1.2.3", // "environment": "production", // "region": "us-east-1", // "uptime_seconds": 3600.5, // "goroutines": 42 // }, // "details": { ... } // } ``` -------------------------------- ### Mixed Execution Models Source: https://context7.com/alexliesenfeld/health/llms.txt Combine synchronous and periodic checks for a balanced approach to health monitoring, optimizing for different check types. ```APIDOC ## GET /health (Mixed Checks) ### Description This configuration demonstrates combining fast synchronous checks (e.g., memory usage) with potentially slower periodic checks (e.g., disk space) to provide a comprehensive and responsive health status. ### Method GET ### Endpoint /health ### Parameters None ### Request Example None ### Response #### Success Response (200) - **status** (string) - Overall health status ('up'). - **details** (object) - Health status of components. - **memory** (object) - **status** (string) - Component status ('up'). - **timestamp** (string) - ISO 8601 timestamp of the check. - **disk-space** (object) - **status** (string) - Component status ('up'). - **timestamp** (string) - ISO 8601 timestamp of the last periodic check. #### Response Example (Success) ```json { "status": "up", "details": { "memory": { "status": "up", "timestamp": "2025-12-04T10:40:00Z" }, "disk-space": { "status": "up", "timestamp": "2025-12-04T10:30:00Z" } } } ``` #### Response Example (One Component Down) ```json { "status": "down", "details": { "memory": { "status": "up", "timestamp": "2025-12-04T10:40:00Z" }, "disk-space": { "status": "down", "timestamp": "2025-12-04T10:30:00Z", "error": "low disk space: 50000000 bytes available" } } } ``` ``` -------------------------------- ### Configure Health Check Caching Source: https://context7.com/alexliesenfeld/health/llms.txt Control how often health checks are performed by configuring cache duration. This balances performance with the freshness of health status. Options include setting a default duration, disabling the cache entirely (not recommended for production), or setting longer durations for less critical checks. ```go // Default: 1 second cache checker := health.NewChecker( health.WithCacheDuration(1*time.Second), health.WithCheck(health.Check{ Name: "database", Check: db.PingContext, }), ) // Disable caching (check on every request - not recommended) checker := health.NewChecker( health.WithDisabledCache(), health.WithCheck(health.Check{ Name: "service", Check: myCheckFunc, }), ) // Longer cache for less critical checks checker := health.NewChecker( health.WithCacheDuration(10*time.Second), health.WithCheck(health.Check{ Name: "metrics-collector", Check: metricsCheck, }), ) ``` -------------------------------- ### Configure Health Check Failure Thresholds Source: https://context7.com/alexliesenfeld/health/llms.txt Configure tolerance for transient failures before marking a component as down. This involves setting `MaxContiguousFails` to require a certain number of consecutive failures and `MaxTimeInError` to enforce a minimum duration of failure, preventing premature alerts for temporary issues. ```go checker := health.NewChecker( health.WithPeriodicCheck(10*time.Second, 0, health.Check{ Name: "flaky-service", Check: externalServiceCheck, // Require 5 consecutive failures before marking as down MaxContiguousFails: 5, // Must be failing for at least 2 minutes before marking as down MaxTimeInError: 2 * time.Minute, }), ) // Component status transitions: // - First failure: status remains "up" (ContiguousFails: 1) // - Failures 2-4: status remains "up" (ContiguousFails: 2-4) // - Fifth failure after 2+ minutes: status becomes "down" // - One success: resets ContiguousFails to 0, status returns to "up" ``` -------------------------------- ### Disable Details in Health Responses in Go Source: https://context7.com/alexliesenfeld/health/llms.txt This Go code illustrates how to configure the health checker to only return the aggregate status ('up' or 'down') in its responses, omitting the details of individual component checks. This is useful for exposing a public health endpoint that should not reveal internal system information. ```go // Full details (default) checker := health.NewChecker( health.WithCheck(health.Check{ Name: "database", Check: db.PingContext, }), ) // Response: {"status": "up", "details": {"database": {"status": "up", ...}}} // Only aggregate status checker := health.NewChecker( health.WithDisabledDetails(), health.WithCheck(health.Check{ Name: "database", Check: db.PingContext, }), ) // Response: {"status": "up"} ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.