healthcheck

package
v1.67.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 27, 2026 License: MIT Imports: 5 Imported by: 0

README

Package healthcheck

Пакет healthcheck предоставляет инструменты для реализации и управления проверками состояния (health checks) в приложениях. Он позволяет регистрировать проверки компонентов, кэшировать результаты и предоставлять их через HTTP-эндпоинт в формате JSON.

Types

Registry

Структура Registry управляет проверками состояния и кэширует их результаты.

Methods:

NewRegistry() *Registry

Конструктор реестра проверок состояния.

(r *Registry) Register(name string, checker Checker)

Зарегистрировать компоненту проверки состояния с именем name. Такой компонентой может быть объект, реализующий интерфейс Checker, либо же функция, обернутая в тип CheckerFunc.

(r *Registry) Handler() http.Handler

HTTP-обработчик для интеграции с HTTP-сервером.

Usage

Default usage flow
package main

import (
	"context"
	"log"
	"net/http"

	"github.com/txix-open/isp-kit/dbrx"
	"github.com/txix-open/isp-kit/grmqx"
	"github.com/txix-open/isp-kit/healthcheck"
	log2 "github.com/txix-open/isp-kit/log"
)

func main() {
	logger, err := log2.New()
	if err != nil {
		log.Fatal(err)
	}
	var (
		dbCli  = dbrx.New(logger)
		rmqCli = grmqx.New(logger)
	)

	registry := healthcheck.NewRegistry()
	registry.Register("database", dbCli)
	registry.Register("mq", rmqCli)
	registry.Register("auth-service", healthcheck.CheckerFunc(func(ctx context.Context) error {
		/* health check auth service */
		return nil
	}))

	/* integration with HTTP-server */
	http.Handle("/health", registry.Handler())
}

Documentation

Overview

Package healthcheck provides utilities for implementing and managing health checks in applications. It allows registering component checks, caching results, and exposing them via an HTTP endpoint in JSON format compliant with the draft-inadarei-api-health-check specification.

Index

Constants

View Source
const (
	// StatusPass indicates a healthy component.
	StatusPass = "pass"
	// StatusFail indicates an unhealthy component.
	StatusFail = "fail"
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Checker

type Checker interface {
	// Healthcheck performs a health check on the component.
	// It returns nil if the component is healthy, or an error otherwise.
	Healthcheck(ctx context.Context) error
}

Checker is the interface that wraps the basic health check method. Implementations should return nil if the component is healthy, or an error describing the problem if it is not.

type CheckerFunc

type CheckerFunc func(ctx context.Context) error

CheckerFunc is a function type that implements the Checker interface. It allows using regular functions as health check implementations.

func (CheckerFunc) Healthcheck

func (r CheckerFunc) Healthcheck(ctx context.Context) error

Healthcheck calls the underlying function f with the provided context.

type Detail

type Detail struct {
	// componentName is the name of the component being checked.
	ComponentName string
	// componentType describes the type of the component.
	ComponentType string
	// status indicates whether the component is healthy ("pass") or unhealthy ("fail").
	Status string
	// output contains additional information about the health check, such as error messages.
	Output string `json:",omitempty"`
	// time is the timestamp when the health check was performed.
	Time time.Time
}

Detail represents the health status of a single component.

nolint:tagliatelle

type Registry

type Registry struct {
	// contains filtered or unexported fields
}

Registry manages a collection of health check components and provides an HTTP handler to expose their status. It caches results to avoid excessive checks.

Registry is safe for concurrent use by multiple goroutines.

func NewRegistry

func NewRegistry(handleTimeout time.Duration) *Registry

NewRegistry creates a new Registry with the specified handle timeout. If handleTimeout is zero, it defaults to 1 second.

func (*Registry) Handler

func (r *Registry) Handler() http.Handler

Handler returns an HTTP handler that exposes the health status of all registered components. The handler returns:

  • 200 OK with status "pass" if all components are healthy
  • 500 Internal Server Error with status "fail" if any component is unhealthy

The response is encoded in application/health+json format according to the draft-inadarei-api-health-check specification.

func (*Registry) Register

func (r *Registry) Register(name string, checker Checker)

Register adds a health check component to the registry. The name parameter is used as the identifier for the component in the results. The checker parameter must implement the Checker interface.

func (*Registry) Unregister added in v1.58.0

func (r *Registry) Unregister(name string)

Unregister removes a health check component from the registry. If the component does not exist, this method has no effect.

type Result

type Result struct {
	// status is the overall health status ("pass" if all components are healthy, "fail" otherwise).
	Status string
	// details maps component names to their individual health details.
	Details map[string][]Detail
}

Result represents the aggregate health status of all registered components.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL