healthz

package
v0.4.2 Latest Latest
Warning

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

Go to latest
Published: Oct 16, 2026 License: MIT Imports: 8 Imported by: 0

Documentation

Overview

Package healthz 提供 ekit 应用健康检查 helper,让业务注册多个 check 项(DB / Redis / 上游依赖等),/healthz endpoint 一次调起,全部通过返 200, 任一失败返 503。

集成方式(hertz):

import "github.com/oekit/bootstrap/bootstrap/healthz"

healthz.RegisterCheck("mysql", func(ctx context.Context) error {
    return db.PingContext(ctx)
})
healthz.RegisterCheck("redis", func(ctx context.Context) error {
    return redisClient.Ping(ctx).Err()
})

h.GET("/healthz", func(_ context.Context, c *app.RequestContext) {
    status, body := healthz.Handle(c)
    c.JSON(status, body)
})

业务使用 liveness/readiness 分离(可选):

  • /healthz — 包含所有 check(默认;所有依赖就绪才返 200)
  • /livez — 只检查进程存活,永远 200(给 K8s livenessProbe)
  • /readyz — 等同 /healthz(给 K8s readinessProbe)

设计:无外部依赖,业务按需注册;包级 singleton(全应用共享一个 registry)。

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DeregisterCheck

func DeregisterCheck(name string)

DeregisterCheck 删除一个 check(测试用,业务不常用)。

func Handle

func Handle(ctx context.Context) (int, string)

Handle 并发执行所有注册的 check。返回 (statusCode, jsonBody) 供 HTTP handler 用。

  • 全部 check 通过 + 未 closed → 200 + "ok"
  • 任一 check 失败 → 503 + 失败详情
  • MarkClosed 已调 → 503 + closed:true

check 用 errgroup-like 模式并发跑,总耗时 = 最慢 check(而非总和), 适合多个外部依赖并行健康检查。整次 Handle 受总超时约束 (默认 5s,SetCheckTimeout 调整/关闭):超时的 check 统一记为 "check timeout",并且每个 check 的 ctx 注入 deadline,支持 ctx 的 依赖(DB Ping 等)能第一时间中止 — 挂死的 check 不再无限阻塞 liveness/readiness 探测(2026-09-05 复审修复)。

func MarkClosed

func MarkClosed()

MarkClosed 把 registry 标记为 closed(应用进入关闭流程), Handle 返 503 + {"status":"unhealthy","closed":true}。常通过 lifecycle.App.AddResource 在关闭序列里调。

func RegisterCheck

func RegisterCheck(name string, check Check)

RegisterCheck 注册一个 check(同名覆盖)。

func ResetForTest

func ResetForTest()

ResetForTest 清空 registry + 重置 closed 标志(仅供 test 使用)。

func SetCheckTimeout

func SetCheckTimeout(d time.Duration)

SetCheckTimeout 调整单次健康检查的总超时(含并发执行的所有 check)。 d <= 0 关闭超时控制(不推荐:挂死的 check 会无限阻塞探测请求)。

Types

type Check

type Check func(ctx context.Context) error

Check 是单个健康检查项。返回 nil 表示通过,error 表示失败 + 原因。

type Result

type Result struct {
	Status string            `json:"status"` // "ok" / "unhealthy"
	Closed bool              `json:"closed"`
	Checks map[string]string `json:"checks,omitempty"` // check name → 错误信息(失败时)
}

Result 是 Handle 的输出(可在 HTTP handler 里转 JSON)。

Jump to

Keyboard shortcuts

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