health: add documentation

This commit is contained in:
Ask Bjørn Hansen 2025-06-06 19:16:14 -07:00
parent faac09ac0c
commit a37559b93e

View File

@ -1,3 +1,9 @@
// Package health provides a standalone HTTP server for health checks.
//
// This package implements a simple health check server that can be used
// to expose health status endpoints for monitoring and load balancing.
// It supports custom health check handlers and provides structured logging
// with graceful shutdown capabilities.
package health package health
import ( import (
@ -11,11 +17,19 @@ import (
"golang.org/x/sync/errgroup" "golang.org/x/sync/errgroup"
) )
// Server is a standalone HTTP server dedicated to health checks.
// It runs separately from the main application server to ensure health
// checks remain available even if the main server is experiencing issues.
//
// The server includes built-in timeouts, graceful shutdown, and structured
// logging for monitoring and debugging health check behavior.
type Server struct { type Server struct {
log *slog.Logger log *slog.Logger
healthFn http.HandlerFunc healthFn http.HandlerFunc
} }
// NewServer creates a new health check server with the specified health handler.
// If healthFn is nil, a default handler that returns HTTP 200 "ok" is used.
func NewServer(healthFn http.HandlerFunc) *Server { func NewServer(healthFn http.HandlerFunc) *Server {
if healthFn == nil { if healthFn == nil {
healthFn = basicHealth healthFn = basicHealth
@ -27,10 +41,13 @@ func NewServer(healthFn http.HandlerFunc) *Server {
return srv return srv
} }
// SetLogger replaces the default logger with a custom one.
func (srv *Server) SetLogger(log *slog.Logger) { func (srv *Server) SetLogger(log *slog.Logger) {
srv.log = log srv.log = log
} }
// Listen starts the health server on the specified port and blocks until ctx is cancelled.
// The server exposes the health handler at "/__health" with graceful shutdown support.
func (srv *Server) Listen(ctx context.Context, port int) error { func (srv *Server) Listen(ctx context.Context, port int) error {
srv.log.Info("starting health listener", "port", port) srv.log.Info("starting health listener", "port", port)
@ -72,8 +89,7 @@ func (srv *Server) Listen(ctx context.Context, port int) error {
return g.Wait() return g.Wait()
} }
// HealthCheckListener runs simple http server on the specified port for // HealthCheckListener runs a simple HTTP server on the specified port for health check probes.
// health check probes
func HealthCheckListener(ctx context.Context, port int, log *slog.Logger) error { func HealthCheckListener(ctx context.Context, port int, log *slog.Logger) error {
srv := NewServer(nil) srv := NewServer(nil)
srv.SetLogger(log) srv.SetLogger(log)