You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
91 lines
1.8 KiB
Go
91 lines
1.8 KiB
Go
package health
|
|
|
|
// Status 健康状态
|
|
type Status string
|
|
|
|
const (
|
|
StatusHealthy Status = "healthy"
|
|
StatusUnhealthy Status = "unhealthy"
|
|
StatusDegraded Status = "degraded"
|
|
)
|
|
|
|
// Check 健康检查接口
|
|
type Check interface {
|
|
// Check 执行健康检查
|
|
Check() (Status, string)
|
|
}
|
|
|
|
// Checker 健康检查器
|
|
type Checker interface {
|
|
// Register 注册健康检查
|
|
Register(name string, check Check) error
|
|
|
|
// Unregister 取消注册健康检查
|
|
Unregister(name string) error
|
|
|
|
// Check 执行所有健康检查
|
|
Check() (Status, map[string]CheckResult)
|
|
}
|
|
|
|
// CheckResult 健康检查结果
|
|
type CheckResult struct {
|
|
Status Status
|
|
Message string
|
|
}
|
|
|
|
// checker 健康检查器实现
|
|
type checker struct {
|
|
checks map[string]Check
|
|
}
|
|
|
|
// NewChecker 创建健康检查器
|
|
func NewChecker() Checker {
|
|
return &checker{
|
|
checks: make(map[string]Check),
|
|
}
|
|
}
|
|
|
|
// Register 注册健康检查
|
|
func (c *checker) Register(name string, check Check) error {
|
|
if name == "" {
|
|
return NewError("check name cannot be empty")
|
|
}
|
|
|
|
if check == nil {
|
|
return NewError("check cannot be nil")
|
|
}
|
|
|
|
c.checks[name] = check
|
|
return nil
|
|
}
|
|
|
|
// Unregister 取消注册健康检查
|
|
func (c *checker) Unregister(name string) error {
|
|
delete(c.checks, name)
|
|
return nil
|
|
}
|
|
|
|
// Check 执行所有健康检查
|
|
func (c *checker) Check() (Status, map[string]CheckResult) {
|
|
results := make(map[string]CheckResult)
|
|
overallStatus := StatusHealthy
|
|
|
|
for name, check := range c.checks {
|
|
status, message := check.Check()
|
|
results[name] = CheckResult{
|
|
Status: status,
|
|
Message: message,
|
|
}
|
|
|
|
// 确定整体状态
|
|
if status == StatusUnhealthy {
|
|
overallStatus = StatusUnhealthy
|
|
} else if status == StatusDegraded && overallStatus == StatusHealthy {
|
|
overallStatus = StatusDegraded
|
|
}
|
|
}
|
|
|
|
return overallStatus, results
|
|
}
|
|
|