actuator

package
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Jul 20, 2026 License: MIT Imports: 18 Imported by: 0

README

actuator 包 — 运维监控端点

所属层级: Infrastructure Layer
设计理念: 生产就绪,可视化监控
设计灵感: Spring Boot Actuator

📖 目录


概述

actuator 包提供类似 Spring Boot Actuator 的运维端点支持,便于在生产环境中监控和管理应用。

核心功能
功能 说明
🔍 健康检查 聚合健康指标,返回整体健康状态
📊 指标收集 收集并返回所有注册的指标
⚙️ 环境信息 显示环境配置源及其属性
📦 Bean 列表 列出 IoC 容器中注册的所有 Bean
🔒 敏感信息过滤 自动检测和掩盖敏感配置信息
🌐 Admin 可视化 Spring Boot Admin 风格的应用管理
子包结构
子包 说明
actuator/ 运维端点管理器(健康检查、指标、环境、Bean 列表)
actuator/health/ 健康检查核心(Indicator 接口、Aggregator 聚合器)
actuator/admin/ Spring Boot Admin 风格可视化监控

快速开始

方式一:自动配置(推荐)

使用 boot 框架,Actuator 会自动配置和挂载:

# application.yaml
actuator:
  enabled: true
package main

import (
    "github.com/xudefa/enhance/boot"
)

func main() {
    app, _ := boot.NewApplication(
        boot.WithAppName("my-app"),
    )
    
    app.Start()
    defer app.Stop()
    
    // Actuator 端点已自动挂载到 HTTP 服务器
    // 访问 http://localhost:8080/actuator/health
}
方式二:手动配置
package main

import (
    "net/http"
    "github.com/xudefa/enhance/actuator"
    "github.com/xudefa/enhance/context"
)

func main() {
    ctx := context.NewApplicationContext(container, env)
    
    // 创建 Actuator
    act := actuator.New(ctx)
    
    // 注册路由
    mux := http.NewServeMux()
    config := actuator.DefaultRouteConfig()
    registrar := &actuator.StdRouteRegistrar{Mux: mux}
    act.RegisterRoutes(registrar, config)
    
    http.ListenAndServe(":8080", mux)
}

可用端点

Actuator 端点
端点 路径 说明
Health /actuator/health 健康检查,聚合所有健康指标
Metrics /actuator/metrics 应用指标
Env /actuator/env 环境信息(自动过滤敏感信息)
Beans /actuator/beans IoC 容器中注册的所有 Bean
Info /actuator/info 应用信息
Prometheus /metrics Prometheus 格式指标
pprof /debug/pprof/* 调试端点(需启用 ExposeDebug)
Admin 可视化端点
端点 方法 说明
/admin/applications GET 列出所有应用
/admin/instances GET 列出所有实例
/admin/instances/{id}/health GET 获取实例健康
/admin/instances/{id}/metrics GET 获取实例指标
/admin/register POST 注册实例
/admin/deregister POST 注销实例

HTTP 端点自动挂载

架构设计

Actuator 使用 HttpEndpointRegistry 接口实现框架无关的端点自动挂载,支持自动挂载到任意 HTTP 框架。

挂载策略(按优先级)
  1. HttpEndpointRegistry 接口(推荐,框架无关)
  2. HttpHandlerRegistry 接口(简化版)
  3. RouteRegistrar 接口(向后兼容)
  4. 独立 HTTP 服务器(降级方案)
已集成的框架
框架 实现位置 状态
Gin starter/gin/endpoint_registry.go ✅ 已集成
Fiber starter/fiber/endpoint_registry.go ✅ 已集成
Echo starter/echo/endpoint_registry.go ✅ 已集成
Chi starter/chi/endpoint_registry.go ✅ 已集成
默认 Router web/mvc/starter.go ✅ 已集成
自动挂载流程
框架 AutoConfig.Configure()
  └─ 创建 XxxEndpointRegistry(engine)
  └─ 注册到容器: HttpEndpointRegistry 类型
  └─ ActuatorHttpStarter.Start()
     └─ 查找 HttpEndpointRegistry
     └─ 自动挂载所有端点
集成新框架

如果您需要将 Actuator 集成到其他 HTTP 框架,请参考以下步骤:

1. 创建 EndpointRegistry 实现
package yourframework

import (
    "net/http"
    "github.com/xudefa/enhance/actuator"
)

type YourFrameworkEndpointRegistry struct {
    engine    *YourEngine
    endpoints map[string]bool
}

func NewYourFrameworkEndpointRegistry(engine *YourEngine) *YourFrameworkEndpointRegistry {
    return &YourFrameworkEndpointRegistry{
        engine:    engine,
        endpoints: make(map[string]bool),
    }
}

func (r *YourFrameworkEndpointRegistry) RegisterEndpoint(method, path string, handler http.Handler) {
    if r.engine == nil || handler == nil {
        return
    }
    
    // 适配框架特定的路由注册
    r.engine.Add(method, path, func(c *Context) {
        handler.ServeHTTP(c.Response(), c.Request())
    })
    r.endpoints[path] = true
}

func (r *YourFrameworkEndpointRegistry) RegisterEndpoints(endpoints []actuator.EndpointConfig) {
    for _, ep := range endpoints {
        r.RegisterEndpoint(ep.Method, ep.Path, ep.Handler)
    }
}

func (r *YourFrameworkEndpointRegistry) HasEndpoint(path string) bool {
    _, exists := r.endpoints[path]
    return exists
}
2. 在 AutoConfig 中注册
func (c *YourFrameworkAutoConfiguration) Configure(ctx boot.ApplicationContext) error {
    // ... 创建框架 engine ...
    
    // 注册 HttpEndpointRegistry
    endpointRegistry := NewYourFrameworkEndpointRegistry(c.engine)
    if err := ctx.Container().RegisterInstance(
        endpointRegistry, 
        reflect.TypeFor[actuator.HttpEndpointRegistry](),
    ); err != nil {
        c.logger.Warn(context.Background(), "注册 HttpEndpointRegistry 失败,Actuator 端点将无法自动挂载",
            log.KeyValue{Key: "error", Value: err.Error()},
        )
    }
    
    return nil
}
3. 验证集成
curl http://localhost:8080/actuator/health
curl http://localhost:8080/actuator/metrics
curl http://localhost:8080/actuator/env

健康检查系统

内置健康指示器
指示器 说明
FuncHealthIndicator 基于函数的通用健康指标
DatabaseHealthIndicator 数据库健康指标
RedisHealthIndicator Redis 健康指标
使用示例
函数健康指标
indicator := actuator.NewFuncHealthIndicator(
    "my-service",
    func(ctx context.Context) error {
        resp, err := http.Get("http://localhost:8080/health")
        if err != nil {
            return err
        }
        defer resp.Body.Close()
        return nil
    },
)
数据库健康指标
indicator := actuator.NewDatabaseHealthIndicator(
    func(ctx context.Context) error {
        return db.PingContext(ctx)
    },
)
Redis 健康指标
indicator := actuator.NewRedisHealthIndicator(
    func(ctx context.Context) error {
        return redisClient.Ping(ctx).Err()
    },
)
Builder 模式

使用 Builder 模式简化健康指示器的创建:

indicator := actuator.NewHealthIndicatorBuilder().
    Name("database").
    CheckFunc(db.Check).
    Timeout(5 * time.Second).
    Detail("type", "postgres").
    Build()
方法 说明
Name(name string) 设置指标名称
CheckFunc(fn) 设置检查函数
Timeout(d) 设置超时时间(默认 5s)
Detail(key, value) 添加详细信息
Build() 构建健康指示器
自定义健康指示器
type customIndicator struct{}

func (c *customIndicator) Name() string { return "custom" }

func (c *customIndicator) Health(ctx context.Context) health.Health {
    // 自定义健康检查逻辑
    return health.Health{
        Status: health.StatusUp,
        Details: map[string]any{
            "version": "1.0.0",
        },
    }
}

// 注册到容器
container.Register(
    reflect.TypeOf(&customIndicator{}),
    core.Bean(&customIndicator{}),
)
检查逻辑

所有内置健康指标统一使用 checkHealth 函数:

  1. checkFnnil → 返回 StatusUnknown
  2. checkFn 返回错误 → 返回 StatusDown,详情中附带错误信息
  3. 检查通过 → 返回 StatusUp

敏感信息保护

默认检测规则

关键词检测:password, secret, token, key, auth, credential, private, api_key, access_token, client_secret, oauth, bearer, jwt

值格式检测:私钥格式、JWT 令牌、长随机字符串

自定义检测策略
type SanitizeStrategy interface {
    IsSensitive(key string, value any) bool
}

sanitizer := actuator.NewSanitizer()
sanitizer.AddStrategy(&myCustomStrategy{})

// 掩盖敏感值
value := sanitizer.Sanitize("db.password", "secret123")
// 返回: "***REDACTED***"
示例:业务特定敏感信息检测
type MyCustomStrategy struct{}

func (s *MyCustomStrategy) IsSensitive(key string, value any) bool {
    return strings.Contains(key, "api-key")
}

sanitizer := actuator.NewSanitizer()
sanitizer.AddStrategy(&MyCustomStrategy{})

配置选项

基础配置
actuator:
  enabled: true              # 启用/禁用 Actuator(默认 true)
  path: /actuator            # 自定义端点路径(默认 /actuator)
端点暴露控制
actuator:
  expose:
    health: true             # 健康检查端点(默认 true)
    metrics: true            # 指标端点(默认 true)
    env: true                # 环境信息端点(默认 true)
    beans: true              # Bean 列表端点(默认 true)
    info: true               # 应用信息端点(默认 true)
    prometheus: true         # Prometheus 端点(默认 true)
独立服务器配置(降级方案)

当无法找到 HTTP 服务器时,Actuator 会启动独立服务器:

actuator:
  host: 0.0.0.0              # 默认 0.0.0.0
  port: 8081                 # 默认 8081
路由配置
type RouteConfig struct {
    BasePath    string  // 基础路径,默认 "/actuator"
    ExposeDebug bool    // 是否暴露调试端点(pprof)
    Prefix      string  // 路径前缀
}

完整示例

package main

import (
    "context"
    "net/http"
    "reflect"

    "github.com/xudefa/enhance/actuator"
    "github.com/xudefa/enhance/boot"
    "github.com/xudefa/enhance/core"
)

func main() {
    app, _ := boot.NewApplication(
        boot.WithAppName("my-app"),
    )
    
    // 注册自定义健康指标
    dbIndicator := actuator.NewDatabaseHealthIndicator(
        func(ctx context.Context) error {
            return db.PingContext(ctx)
        },
    )
    app.Container().Register(
        reflect.TypeOf(dbIndicator),
        core.Bean(dbIndicator),
    )
    
    redisIndicator := actuator.NewRedisHealthIndicator(
        func(ctx context.Context) error {
            return redisClient.Ping(ctx).Err()
        },
    )
    app.Container().Register(
        reflect.TypeOf(redisIndicator),
        core.Bean(redisIndicator),
    )
    
    app.Start()
    defer app.Stop()
    
    // Actuator 端点已自动挂载
    // 访问 http://localhost:8080/actuator/health
}

最佳实践

✅ 1. 生产环境启用 Actuator
actuator:
  enabled: true
✅ 2. 保护 Actuator 端点
security.AuthorizeRequests(func(reg security.AuthorizeRequests) {
    reg.AntMatchers("/actuator/**").HasRole("ADMIN")
    reg.AnyRequest().Authenticated()
})
✅ 3. 监控关键依赖
// 为所有关键依赖添加健康检查
indicator := actuator.NewDatabaseHealthIndicator(
    func(ctx context.Context) error {
        return db.PingContext(ctx)
    },
)
container.Register(
    reflect.TypeOf(indicator),
    core.Bean(indicator),
)
✅ 4. 生产环境禁用调试端点
config := actuator.DefaultRouteConfig()
config.ExposeDebug = false  // 生产环境禁用 pprof
✅ 5. 始终注册 HttpEndpointRegistry

确保 Actuator 端点能自动挂载到 HTTP 框架:

endpointRegistry := NewYourFrameworkEndpointRegistry(c.engine)
ctx.Container().RegisterInstance(
    endpointRegistry, 
    reflect.TypeFor[actuator.HttpEndpointRegistry](),
)

故障排查

Actuator 端点未挂载
  1. ✅ 检查 actuator.enabled 是否为 true
  2. ✅ 检查框架是否注册了 HttpEndpointRegistry
  3. ✅ 查看日志中是否有 "Started standalone server" 消息
使用独立服务器

如果日志显示 "Started standalone server on :8081",说明 Actuator 未能找到 HTTP 服务器,使用了降级方案。

常见原因

  • 框架的 autoconfig 未注册 HttpEndpointRegistry
  • 框架的 autoconfig 执行顺序在 actuator-http 之后

解决方案

// 在框架的 autoconfig 中手动注册
registry := NewYourFrameworkEndpointRegistry(engine)
ctx.Container().RegisterInstance(registry, reflect.TypeFor[actuator.HttpEndpointRegistry]())
敏感信息泄露

检查 /actuator/env 端点返回的数据,确保敏感信息已被掩盖:

curl http://localhost:8080/actuator/env | grep -i password
# 应该返回 "***REDACTED***" 而非真实密码

如需添加自定义敏感信息检测策略,参考 敏感信息保护 章节。

Documentation

Overview

Package actuator 提供应用监控端点 Starter,用于 enhance 框架。

该模块提供多种运维监控端点,包括健康检查、指标收集、环境信息等。 支持多种 HTTP 框架集成,如标准库 http、Gin、Hertz 等。

架构设计

  • Actuator: 运维端点管理器
  • health.Aggregator: 健康检查聚合器
  • metrics.MeterRegistry: 指标注册表
  • Sanitizer: 敏感信息检测器

支持的端点

  • /health: 健康检查
  • /info: 应用信息
  • /metrics: 指标暴露
  • /env: 环境配置查看
  • /beans: Bean 列表
  • /admin: 管理端点

使用方式

在 main.go 中引入:

import _ "github.com/xudefa/enhance/actuator"

配置属性

  • actuator.enabled: 是否启用监控端点(默认 true)
  • actuator.path: 端点路径前缀(默认 /actuator)
  • actuator.health.enabled: 是否启用健康检查(默认 true)
  • actuator.metrics.enabled: 是否启用指标收集(默认 true)

配置示例

环境变量:

export ACTUATOR_ENABLED=true
export ACTUATOR_PATH=/actuator

配置文件(application.json):

{
  "actuator": {
    "enabled": true,
    "path": "/actuator",
    "health": {
      "enabled": true
    },
    "metrics": {
      "enabled": true
    }
  }
}

Index

Constants

View Source
const (
	// 应用配置
	AppName    = "app.name"
	AppVersion = "app.version"

	// Actuator 配置
	ActuatorEnabled = "actuator.enabled"
)
View Source
const (
	// 应用默认值
	DefaultAppName    = "enhance-app"
	DefaultAppVersion = "1.0.0"

	// 条件值常量
	ConditionTrue = "true"
)

Variables

This section is empty.

Functions

func EnsureLeadingSlash

func EnsureLeadingSlash(path string) string

EnsureLeadingSlash 确保路径以 / 开头

func JoinPath

func JoinPath(base, path string) string

JoinPath 拼接路径

func NewDatabaseHealthIndicator

func NewDatabaseHealthIndicator(checkFunc func(context.Context) error) health.Indicator

NewDatabaseHealthIndicator 创建数据库健康指示器

func NewRedisHealthIndicator

func NewRedisHealthIndicator(checkFunc func(context.Context) error) health.Indicator

NewRedisHealthIndicator 创建Redis健康指示器

Types

type Actuator

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

Actuator 运维端点管理器

提供多种运维端点,包括健康检查、指标收集、环境信息、Bean 列表等。 支持多种 HTTP 框架集成,如标准库 http、Gin、Hertz 等。

func New

func New(ctx AppContext) *Actuator

New 创建 Actuator 实例

func (*Actuator) BeansHandler

func (a *Actuator) BeansHandler(w http.ResponseWriter, r *http.Request)

BeansHandler Bean 列表 HTTP 处理器

func (*Actuator) EnvHandler

func (a *Actuator) EnvHandler(w http.ResponseWriter, r *http.Request)

EnvHandler 环境信息 HTTP 处理器

func (*Actuator) HealthHandler

func (a *Actuator) HealthHandler(w http.ResponseWriter, r *http.Request)

HealthHandler 健康检查 HTTP 处理器

返回聚合后的健康状态信息,包含所有健康指标的详细状态。 响应格式:

{
  "status": "UP",
  "details": {
    "database": {
      "status": "UP",
      "detail": {}
    }
  },
  "timestamp": "2024-01-01T00:00:00Z"
}

func (*Actuator) InfoHandler

func (a *Actuator) InfoHandler(w http.ResponseWriter, r *http.Request)

InfoHandler 应用信息 HTTP 处理器

func (*Actuator) MetricsHandler

func (a *Actuator) MetricsHandler(w http.ResponseWriter, r *http.Request)

MetricsHandler 指标 HTTP 处理器

func (*Actuator) MetricsRegistry

func (a *Actuator) MetricsRegistry() metrics.MeterRegistry

MetricsRegistry 获取指标注册表

func (*Actuator) PprofHandlers

func (a *Actuator) PprofHandlers() map[string]http.HandlerFunc

PprofHandlers returns handlers for pprof endpoints

func (*Actuator) PrometheusHandler

func (a *Actuator) PrometheusHandler(w http.ResponseWriter, r *http.Request)

PrometheusHandler Prometheus 指标 HTTP 处理器

func (*Actuator) RegisterDebugRoutes

func (a *Actuator) RegisterDebugRoutes(registrar RouteRegistrar)

RegisterDebugRoutes 注册调试路由

func (*Actuator) RegisterRoutes

func (a *Actuator) RegisterRoutes(registrar RouteRegistrar, config RouteConfig)

RegisterRoutes 注册 Actuator 路由

使用 RouteRegistrar 接口解耦路由注册逻辑, 支持不同的 HTTP 框架实现。

func (*Actuator) SetHealthAggregator

func (a *Actuator) SetHealthAggregator(agg *health.Aggregator)

SetHealthAggregator 设置健康检查聚合器

func (*Actuator) SetMetricsRegistry

func (a *Actuator) SetMetricsRegistry(reg metrics.MeterRegistry)

SetMetricsRegistry 设置指标注册表

type ActuatorAutoConfiguration

type ActuatorAutoConfiguration struct{}

ActuatorAutoConfiguration Actuator 自动配置

func (*ActuatorAutoConfiguration) Configure

Configure 创建 Actuator 实例并注册为 Bean

type ActuatorHttpStarter

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

ActuatorHttpStarter Actuator HTTP 启动器

负责将 Actuator 端点自动挂载到现有的 HTTP 服务器上。 通过 HttpEndpointRegistry 接口实现框架无关的端点注册, 支持任意 HTTP 框架(Gin、Fiber、Echo、Chi 等)。

挂载策略(按优先级): 1. HttpEndpointRegistry 接口(推荐,框架无关) 2. HttpHandlerRegistry 接口(简化版) 3. RouteRegistrar 接口(向后兼容) 4. 独立 HTTP 服务器(降级方案)

通过配置项控制各端点的暴露:

  • actuator.expose.health: 健康检查端点(默认 true)
  • actuator.expose.metrics: 指标端点(默认 true)
  • actuator.expose.env: 环境信息端点(默认 true)
  • actuator.expose.beans: Bean 列表端点(默认 true)
  • actuator.expose.info: 应用信息端点(默认 true)
  • actuator.expose.prometheus: Prometheus 端点(默认 true)

func (*ActuatorHttpStarter) Configure

Configure 配置阶段:从容器中获取 Actuator 实例

func (*ActuatorHttpStarter) Dependencies

func (s *ActuatorHttpStarter) Dependencies() []string

Dependencies 返回依赖的其他启动器名称

func (*ActuatorHttpStarter) GetCondition

func (s *ActuatorHttpStarter) GetCondition() condition.Condition

GetCondition 返回启动条件

func (*ActuatorHttpStarter) Name

func (s *ActuatorHttpStarter) Name() string

Name 返回启动器名称

func (*ActuatorHttpStarter) Start

Start 启动阶段:将 Actuator 端点挂载到 HTTP 服务器

func (*ActuatorHttpStarter) Stop

Stop 停止阶段:无需特殊处理

type AppContext

type AppContext interface {
	Container() core.Container
	Environment() *environment.Environment
}

AppContext 应用上下文接口。

type DiskSpaceHealthIndicator

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

DiskSpaceHealthIndicator 磁盘空间健康指标

检查磁盘使用率是否超过阈值,当使用率过高时返回降级状态。

func NewDiskSpaceHealthIndicator

func NewDiskSpaceHealthIndicator(path string, threshold float64) *DiskSpaceHealthIndicator

NewDiskSpaceHealthIndicator 创建磁盘空间健康指标

参数:

  • path: 检查的磁盘路径
  • threshold: 使用率阈值(0.0-1.0),超过此比例返回降级状态

func (*DiskSpaceHealthIndicator) Health

Health 执行磁盘空间健康检查

func (*DiskSpaceHealthIndicator) Name

func (d *DiskSpaceHealthIndicator) Name() string

Name 返回健康指标名称

type EndpointConfig

type EndpointConfig struct {
	// Method HTTP 方法,空字符串表示所有方法
	Method string

	// Path 路由路径
	Path string

	// Handler HTTP 处理器
	Handler http.Handler

	// Description 端点描述(可选,用于日志和文档)
	Description string
}

EndpointConfig 端点配置

type HttpEndpointRegistry

type HttpEndpointRegistry interface {
	// RegisterEndpoint 注册单个端点
	// method: HTTP 方法(GET, POST 等),空字符串表示所有方法
	// path: 路由路径
	// handler: HTTP 处理器
	RegisterEndpoint(method, path string, handler http.Handler)

	// RegisterEndpoints 批量注册端点
	// endpoints: 端点配置列表
	RegisterEndpoints(endpoints []EndpointConfig)

	// HasEndpoint 检查是否已注册指定路径的端点
	HasEndpoint(path string) bool
}

HttpEndpointRegistry HTTP 端点注册表接口

该接口作为 Web 框架和 Actuator 之间的桥梁,允许 Actuator 将端点 挂载到任意 HTTP 框架,而无需关心框架的具体实现细节。

Web 框架(如 Gin、Fiber、默认 Router 等)应在启动时向容器注册 此接口的实现,Actuator 通过查找此接口来自动挂载端点。

使用示例(Gin 框架):

registry := &GinEndpointRegistry{engine: ginEngine}
ctx.Container().RegisterInstance(registry, reflect.TypeFor[actuator.HttpEndpointRegistry]())

使用示例(Fiber 框架):

registry := &FiberEndpointRegistry{app: fiberApp}
ctx.Container().RegisterInstance(registry, reflect.TypeFor[actuator.HttpEndpointRegistry]())

type HttpEndpointRegistryAdapter

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

HttpEndpointRegistryAdapter HttpEndpointRegistry 的基础实现

该适配器将 HttpEndpointRegistry 接口委托给底层的 HttpHandlerRegistry, 为不同 HTTP 框架提供统一的注册方式。

框架集成者可以实现 HttpHandlerRegistry 接口,然后使用此适配器 快速获得 HttpEndpointRegistry 的完整功能。

func NewHttpEndpointRegistryAdapter

func NewHttpEndpointRegistryAdapter(registry HttpHandlerRegistry) *HttpEndpointRegistryAdapter

NewHttpEndpointRegistryAdapter 创建 HttpEndpointRegistry 适配器

func (*HttpEndpointRegistryAdapter) HasEndpoint

func (a *HttpEndpointRegistryAdapter) HasEndpoint(path string) bool

HasEndpoint 检查是否已注册指定路径的端点

func (*HttpEndpointRegistryAdapter) RegisterEndpoint

func (a *HttpEndpointRegistryAdapter) RegisterEndpoint(method, path string, handler http.Handler)

RegisterEndpoint 注册单个端点

func (*HttpEndpointRegistryAdapter) RegisterEndpoints

func (a *HttpEndpointRegistryAdapter) RegisterEndpoints(endpoints []EndpointConfig)

RegisterEndpoints 批量注册端点

type HttpHandlerRegistry

type HttpHandlerRegistry interface {
	// Handle 注册路由处理器
	// pattern: 路由模式,如 "/actuator/health"
	// handler: HTTP 处理器
	Handle(pattern string, handler http.Handler)
}

HttpHandlerRegistry HTTP Handler 注册表

这是 HttpEndpointRegistry 的简化版本,仅支持注册 http.Handler。 适用于只需要基本路由注册功能的场景。

type MemoryHealthIndicator

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

MemoryHealthIndicator 内存使用健康指标

检查内存使用情况,当使用率过高时返回降级状态。

func NewMemoryHealthIndicator

func NewMemoryHealthIndicator(threshold float64) *MemoryHealthIndicator

NewMemoryHealthIndicator 创建内存健康指标

参数:

  • threshold: 堆内存使用率阈值(0.0-1.0),超过此比例返回降级状态

func (*MemoryHealthIndicator) Health

Health 执行内存使用健康检查

func (*MemoryHealthIndicator) Name

func (m *MemoryHealthIndicator) Name() string

Name 返回健康指标名称

type PathNormalizer

type PathNormalizer struct{}

PathNormalizer 路径标准化工具

func (PathNormalizer) NormalizePath

func (PathNormalizer) NormalizePath(path string) string

NormalizePath 标准化路径,确保路径格式正确

type ProcessHealthIndicator

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

ProcessHealthIndicator 进程健康指标

检查进程状态信息,如goroutine数量等。

func NewProcessHealthIndicator

func NewProcessHealthIndicator(goroutineThreshold int) *ProcessHealthIndicator

NewProcessHealthIndicator 创建进程健康指标

参数:

  • goroutineThreshold: goroutine 数量阈值,超过此值返回降级状态

func (*ProcessHealthIndicator) Health

Health 执行进程状态健康检查

func (*ProcessHealthIndicator) Name

func (p *ProcessHealthIndicator) Name() string

Name 返回健康指标名称

type RouteConfig

type RouteConfig struct {
	BasePath    string
	ExposeDebug bool
	Prefix      string
}

RouteConfig 路由配置

func DefaultRouteConfig

func DefaultRouteConfig() RouteConfig

DefaultRouteConfig 返回默认路由配置

type RouteRegistrar

type RouteRegistrar interface {
	Handle(pattern string, handler http.Handler)
}

RouteRegistrar 路由注册器接口。

type SanitizeStrategy

type SanitizeStrategy interface {
	IsSensitive(key string, value any) bool
}

SanitizeStrategy 敏感信息检测策略接口。

type Sanitizer

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

Sanitizer 敏感信息检测器

使用策略模式管理多种敏感信息检测规则, 支持自定义检测策略。 使用 atomic.Value 优化高频读取场景的性能。

func NewSanitizer

func NewSanitizer() *Sanitizer

NewSanitizer 创建敏感信息检测器

func (*Sanitizer) AddStrategy

func (s *Sanitizer) AddStrategy(strategy SanitizeStrategy)

AddStrategy 添加自定义检测策略

func (*Sanitizer) Sanitize

func (s *Sanitizer) Sanitize(key string, value any) any

Sanitize 掩盖敏感值

type StdHttpHandlerRegistry

type StdHttpHandlerRegistry struct {
	Mux interface {
		Handle(pattern string, handler http.Handler)
	}
}

StdHttpHandlerRegistry 标准库 http.Handler 注册表实现

该实现包装 http.ServeMux 或其他实现了 Handle 方法的类型, 提供 HttpHandlerRegistry 接口的功能。

func (*StdHttpHandlerRegistry) Handle

func (r *StdHttpHandlerRegistry) Handle(pattern string, handler http.Handler)

Handle 注册路由处理器

type StdRouteRegistrar

type StdRouteRegistrar struct {
	Mux interface {
		Handle(pattern string, handler http.Handler)
	}
}

StdRouteRegistrar 标准库 HTTP 路由注册器

该实现包装 http.ServeMux,提供 RouteRegistrar 接口的功能。

func (*StdRouteRegistrar) Handle

func (r *StdRouteRegistrar) Handle(pattern string, handler http.Handler)

Handle 注册路由处理器

Directories

Path Synopsis
Package health 提供健康检查功能,用于 enhance 框架。
Package health 提供健康检查功能,用于 enhance 框架。

Jump to

Keyboard shortcuts

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