httpserver

package
v1.4.0 Latest Latest
Warning

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

Go to latest
Published: Mar 19, 2026 License: Apache-2.0 Imports: 13 Imported by: 0

README

HTTPServer 包

httpserver 是基于 Gin 的 HTTP 传输层封装,目标是保留 Gin 的灵活性,同时提供更稳定的服务启动、健康检查和 typed handler 能力,方便业务项目统一接入,也方便 AI coding 理解和生成代码。

适用场景

  • 需要一个轻量 HTTP 服务启动器
  • 需要保留 Gin 原生路由写法
  • 需要模块化注册路由
  • 需要统一的 JSON / Query / URI typed handler 写法
  • 需要把日志、指标、审计接入到自己的实现,而不是绑定框架内置日志

安装

go get github.com/tsopia/go-kit/httpserver

核心能力

  • NewServer 创建 HTTP 服务
  • Start / Serve / Run / Shutdown 生命周期管理
  • HealthCheckPort 支持独立健康检查端口
  • Hooks 支持生命周期事件观测
  • RouteModule 支持按模块注册路由
  • Handle / HandleJSON 支持 typed handler
  • DecodeJSON / DecodeQuery / DecodeURI / ComposeDecoder 支持请求解码组合
  • httpserver/middleware 子包支持通用 Recovery、Timeout、TraceID、RequestID、AccessLog、Compression、ConcurrencyLimit、CORS 等中间件
  • httpserver/observability/prometheushttpserver/observability/otel 子包支持指标和 tracing 集成
  • httpserver/preset 子包支持官方推荐的默认装配
  • httpserver/integration/errorsx 子包支持 errors 包到 typed handler 的统一错误映射
  • httpserver/swagger 子包支持 Swagger UI 路由挂载

快速开始

直接使用 Gin 风格路由
package main

import (
	"log"

	"github.com/gin-gonic/gin"
	"github.com/tsopia/go-kit/httpserver"
)

func main() {
	srv := httpserver.NewServer(&httpserver.Config{
		Host: "0.0.0.0",
		Port: 8080,
	})

	srv.GET("/healthz", func(c *gin.Context) {
		c.JSON(200, gin.H{"status": "ok"})
	})

	if err := srv.Run(); err != nil {
		log.Fatal(err)
	}
}
推荐的 typed handler 写法
package main

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

	"github.com/gin-gonic/gin"
	"github.com/tsopia/go-kit/httpserver"
)

type LoginRequest struct {
	Email string `json:"email"`
}

func (r LoginRequest) Validate() error {
	if r.Email == "" {
		return fmt.Errorf("email is required")
	}
	return nil
}

type LoginResponse struct {
	Token string `json:"token"`
}

type AuthService struct{}

func (s *AuthService) Login(ctx context.Context, req LoginRequest) (LoginResponse, error) {
	return LoginResponse{Token: "token-123"}, nil
}

type UserModule struct {
	auth *AuthService
}

func NewUserModule(auth *AuthService) *UserModule {
	return &UserModule{auth: auth}
}

func (m *UserModule) RegisterRoutes(r gin.IRoutes) {
	r.POST("/login", httpserver.HandleJSON(
		m.Login,
		httpserver.WithSuccessStatus(http.StatusOK),
	))
}

func (m *UserModule) Login(ctx context.Context, req LoginRequest) (LoginResponse, error) {
	return m.auth.Login(ctx, req)
}

func main() {
	srv := httpserver.NewServer(nil, httpserver.WithModules(
		NewUserModule(&AuthService{}),
	))

	if err := srv.Run(); err != nil {
		log.Fatal(err)
	}
}

配置

type Config struct {
	Host            string
	Port            int
	ReadTimeout       time.Duration
	ReadHeaderTimeout time.Duration
	WriteTimeout      time.Duration
	IdleTimeout       time.Duration
	MaxHeaderBytes    int
	ShutdownTimeout time.Duration
	DrainTimeout      time.Duration

	EnableHealthCheck bool
	HealthCheckPath   string
	ReadinessPath     string
	LivenessPath      string
	HealthCheckPort   int
}

默认值可以通过 httpserver.DefaultConfig() 获取。 如果需要对传入配置补默认值或做启动前校验,可使用 (*Config).Normalize()(*Config).Validate()

生命周期与 hooks

如果你需要日志、指标或审计,使用 Hooks 接入你自己的实现:

srv := httpserver.NewServer(cfg, httpserver.WithHooks(httpserver.Hooks{
	OnStarted: func(ctx context.Context, event httpserver.LifecycleEvent) {
		log.Printf("server started addr=%s health=%s", event.Addr, event.HealthAddr)
	},
	OnServeError: func(ctx context.Context, event httpserver.LifecycleEvent) {
		log.Printf("server error addr=%s err=%v", event.Addr, event.Err)
	},
	OnStateChange: func(ctx context.Context, from httpserver.State, to httpserver.State) {
		log.Printf("state changed: %s -> %s", from, to)
	},
}))

httpserver 不依赖 kit 或任何具体日志包,日志方案由使用方决定。

通用中间件

如果你需要可复用的 Recovery、Timeout、TraceID、RequestID、AccessLog、Compression、ConcurrencyLimit、CORS 或安全响应头,优先使用 httpserver/middleware 子包,而不是继续向 Server 主类型增加能力。

其中 Timeout 是协作式执行预算,不是 goroutine 强制终止器;它通过 context.Context 向下游传播 deadline。ConcurrencyLimit 统计的是仍在执行中的 handler 数量,因此和 Timeout 组合时,槽位释放以“请求执行结束”为准,而不是以“客户端已经收到 504”为准。

srv := httpserver.NewServer(cfg)
srv.Use(middleware.Recovery())
srv.Use(middleware.AccessLog())
srv.Use(middleware.Compression())
srv.Use(middleware.ConcurrencyLimit(100))
srv.Use(middleware.Timeout(2 * time.Second))
srv.Use(middleware.TraceID())

如果你需要限制单进程内的全局并发并在超限时立即返回 503,可以使用 ConcurrencyLimit

srv.Use(middleware.ConcurrencyLimit(100))
CORS
srv.Use(middleware.CORS(middleware.CORSConfig{
    AllowOrigins:     []string{"https://app.example.com"},
    AllowMethods:     "GET, POST, PUT, DELETE, OPTIONS",
    AllowHeaders:     "Content-Type, Authorization",
    AllowCredentials: true,
    MaxAge:           3600 * time.Second,
}))
Rate Limit
// 简单限流:每秒 100 请求
srv.Use(middleware.RateLimit(100))

// 自定义配置
srv.Use(middleware.RateLimitWithConfig(middleware.RateLimitConfig{
    Rate:  10,
    Burst: 20,
    OnRejected: func(c *gin.Context) {
        c.JSON(429, gin.H{"error": "rate limited"})
    },
}))

如果需要调试请求体和响应体,可以显式开启 payload capture:

srv.Use(middleware.AccessLog(middleware.AccessLogConfig{
	CapturePayload: true,
	MaxBodyBytes:   8 << 10,
	Multipart: middleware.MultipartConfig{
		Mode: middleware.MultipartFormFieldsOnly,
	},
}))

如果需要响应压缩,可以显式挂载:

srv.Use(middleware.Compression())

可观测性扩展

如果你需要指标和 tracing,请使用独立的 observability 子包,而不是把这些能力塞进 httpserver core。

public := srv.Group("")
srv.Use(prometheus.Middleware())
srv.Use(otel.Middleware(otel.Config{
	TracerName: "user-service",
}))
prometheus.Register(public, prometheus.Config{
	Path: "/metrics",
})

官方默认装配

如果你希望快速获得一套一致的 HTTP 默认链路,可以直接使用 httpserver/preset

srv := preset.NewProductionServer(cfg)

健康检查

共享主端口:

srv := httpserver.NewServer(&httpserver.Config{
	Host:              "0.0.0.0",
	Port:              8080,
	EnableHealthCheck: true,
	HealthCheckPath:   "/healthz",
})

独立健康检查端口:

srv := httpserver.NewServer(&httpserver.Config{
	Host:              "0.0.0.0",
	Port:              8080,
	EnableHealthCheck: true,
	HealthCheckPath:   "/healthz",
	HealthCheckPort:   18080,
})

默认情况下,服务器启动后会自动进入 ready 状态,同时暴露:

  • HealthCheckPath,默认 /health
  • ReadinessPath,默认 /readyz
  • LivenessPath,默认 /livez

如果你需要自定义 HealthCheckPath,应优先在 Config 中传入,或在健康检查路由尚未注册前调用 SetHealthCheckPath(...)。一旦 health/readiness/liveness 路由已经注册,SetHealthCheckPath(...) 会返回错误,避免配置值与真实路由脱节。

如果你需要在预热完成后再接流量,可以通过 httpserver.WithManualReadiness() 关闭自动 ready,然后在合适时机调用 srv.MarkReady()MarkReady() / MarkDraining() 现在会在非法状态迁移时返回 error,而不是 panic。

模块化路由

如果希望按业务模块组织路由,实现 RouteModule 即可:

type RouteModule interface {
	RegisterRoutes(r gin.IRoutes)
}

推荐在应用装配层完成依赖注入,再把模块交给 httpserver

userRepo := NewUserRepo(db)
authSvc := NewAuthService(userRepo)
userModule := NewUserModule(authSvc)

srv := httpserver.NewServer(cfg, httpserver.WithModules(userModule))

Typed handler

常用快捷入口:

r.POST("/login", httpserver.HandleJSON(login))
r.GET("/users", httpserver.HandleQuery(listUsers))
r.GET("/users/:id", httpserver.HandleURI(getUser))
r.GET("/users/:id", httpserver.HandleQueryURI(getUserDetail))

// 支持 Form/Multipart 自动识别
r.POST("/upload", httpserver.HandleForm(uploadHandler))

// 无响应体操作(默认返回 204)
r.DELETE("/items/:id", httpserver.HandleNoContent(deleteItem))

可用 decoder:

httpserver.DecodeJSON[Req]()   // JSON body
httpserver.DecodeQuery[Req]()  // Query string
httpserver.DecodeURI[Req]()    // URI 参数
httpserver.DecodeForm[Req]()   // JSON/Form/Multipart 自动识别
httpserver.DecodeHeader[Req]() // Header

如果你需要更细粒度的解码控制,仍然可以保留底层 decoder 组合:

r.GET("/users", httpserver.Handle(
	listUsers,
	httpserver.WithDecoder(httpserver.DecodeQuery[ListUsersRequest]()),
))

httpserver.ComposeDecoder(
	httpserver.DecodeURI[Req](),
	httpserver.DecodeQuery[Req](),
)

请求对象如果实现了以下任一方法,会自动执行校验:

Validate() error
Validate(context.Context) error

如果还需要补充装配层校验,可以追加显式 validator:

r.POST("/register", httpserver.HandleJSON(
	register,
	httpserver.WithValidators(func(ctx context.Context, req RegisterRequest) error {
		if strings.HasSuffix(req.Email, "@company.com") {
			return nil
		}

		return &httpserver.ValidationError{
			Message: "request validation failed",
			Fields: []httpserver.ValidationField{
				{
					Field:   "email",
					Message: "must use company email",
				},
			},
		}
	}),
))

默认错误响应统一为:

{
  "code": "validation_failed",
  "message": "email is required"
}

字段级校验会额外返回 details.fields。如果业务错误需要自己控制 HTTP 状态码和错误体语义,可以返回实现了 HTTPError 接口的错误,或者继续通过 WithErrorMapper(...) 做项目级映射。

如果团队统一使用 github.com/tsopia/go-kit/errors 作为业务错误出口,推荐直接使用 httpserver/integration/errorsx

import (
	"github.com/tsopia/go-kit/httpserver"
	"github.com/tsopia/go-kit/httpserver/integration/errorsx"
)

r.POST("/users", httpserver.HandleJSON(
	createUser,
	httpserver.WithErrorMapper(errorsx.Mapper()),
))

默认会把 errors 包中的业务错误映射成:

{
  "code": 2002,
  "name": "INVALID_PARAM",
  "message": "email is required"
}

Swagger 集成

推荐通过 httpserver/swagger 子包挂载 Swagger UI,而不是把文档路由和业务鉴权揉在一起。

安装依赖:

go get github.com/tsopia/go-kit/httpserver/swagger
go install github.com/swaggo/swag/cmd/swag@latest

生成文档:

swag init -g cmd/server/main.go -o internal/docs

推荐路由组织:

import (
	_ "your/module/internal/docs"

	"github.com/tsopia/go-kit/httpserver"
	httpswagger "github.com/tsopia/go-kit/httpserver/swagger"
)

srv := httpserver.NewServer(nil)

public := srv.Group("")
protected := srv.Group("/api/v1")
protected.Use(AuthMiddleware())

httpswagger.Register(public, httpswagger.Config{})

推荐约定:

  • Swagger 默认公开访问,注册在 public 路由组
  • 业务鉴权只挂到受保护的 Group(),不要直接全局 srv.Use(AuthMiddleware())
  • 历史项目如果已经使用全局鉴权,中间件需要对白名单路径 /swagger/ 放行
  • swaggo 注释写在 transport 层 typed handler 上,不写在 service 层
Swagger 注释模板

推荐把 swaggo 注释写在被 Handle... 包装的 handler 上:

type LoginRequest struct {
	Email string `json:"email" binding:"required"`
}

type LoginResponse struct {
	Token string `json:"token"`
}

// login godoc
// @Summary 用户登录
// @Description 使用邮箱登录并返回访问令牌
// @Tags auth
// @Accept json
// @Produce json
// @Param request body LoginRequest true "登录请求"
// @Success 200 {object} LoginResponse
// @Failure 400 {object} httpserver.ErrorResponse
// @Failure 422 {object} httpserver.ErrorResponse
// @Failure 500 {object} httpserver.ErrorResponse
// @Router /auth/login [post]
func (m *UserModule) login(ctx context.Context, req LoginRequest) (LoginResponse, error) {
	return m.auth.Login(ctx, req)
}

r.POST("/auth/login", httpserver.HandleJSON(m.login))

鉴权接口模板:

// profile godoc
// @Summary 获取当前用户信息
// @Tags user
// @Produce json
// @Security BearerAuth
// @Success 200 {object} ProfileResponse
// @Failure 401 {object} httpserver.ErrorResponse
// @Failure 403 {object} httpserver.ErrorResponse
// @Failure 500 {object} httpserver.ErrorResponse
// @Router /users/me [get]
func (m *UserModule) profile(ctx context.Context, req ProfileRequest) (ProfileResponse, error) {
	return m.user.Profile(ctx, req)
}

Query 接口模板:

type ListUsersRequest struct {
	Page int `form:"page"`
	Size int `form:"size"`
}

// listUsers godoc
// @Summary 用户列表
// @Tags user
// @Produce json
// @Param page query int false "页码"
// @Param size query int false "每页数量"
// @Security BearerAuth
// @Success 200 {object} ListUsersResponse
// @Failure 400 {object} httpserver.ErrorResponse
// @Failure 500 {object} httpserver.ErrorResponse
// @Router /users [get]
func (m *UserModule) listUsers(ctx context.Context, req ListUsersRequest) (ListUsersResponse, error) {
	return m.user.List(ctx, req)
}

推荐实践

  • 需要灵活性时,直接使用 Gin 原生 handler
  • 需要统一接口契约时,优先使用 HandleJSONHandleQueryHandleURIHandleQueryURI
  • 模块依赖在业务装配层注入,不在 httpserver 内做容器
  • 日志、指标、审计统一通过 Hooks 接入
  • Swagger 建议通过 httpserver/swagger 注册在公共路由组

设计约束与已知问题

以下问题将在 Server Core 重构中解决:

IsRunning() 语义

已实现IsRunning() 基于 State() 判断:

  • StateReadyStateDraining 时返回 true
  • Shutdown() 后状态变为 StateStoppedIsRunning() 返回 false
DrainTimeout 配置

已实现WaitForShutdown() 收到信号后:

  1. 先调用 MarkDraining(),readiness 立即返回 503
  2. 等待 DrainTimeout 时间
  3. 然后进入 Shutdown()
HealthAddr() 方法

已实现HealthAddr() 方法返回健康检查地址:

  • 健康检查禁用时返回空字符串
  • 共享端口时返回主服务器地址
  • 独立端口时返回独立地址
http.Server Mutator

已实现WithHTTPServerMutator(func(*http.Server)) Option 允许在 http.Server 创建后、启动前修改底层配置。

更多说明

更完整的设计说明与用法参考见:

  • docs/httpserver.md
  • examples/http-server
  • examples/http-server-improved
  • examples/http-health-check

Documentation

Overview

Package httpserver 提供基于 Gin 的 HTTP 服务封装。

支持直接使用 Gin 风格注册路由,也支持通过 typed handler 统一请求解码与响应编码。

基本使用:

srv := httpserver.NewServer(&httpserver.Config{
    Port: 8080,
})

srv.GET("/healthz", func(c *gin.Context) {
    c.JSON(200, gin.H{"status": "ok"})
})

Typed handler:

srv.POST("/login", httpserver.HandleJSON(login))

生命周期管理:

srv.Run()                              // 阻塞启动
srv.Start()                            // 非阻塞启动
srv.WaitForShutdown()                  // 等待信号并优雅关闭

服务器状态:

srv.State()      // 获取当前状态: new/starting/ready/draining/stopping/stopped/failed
srv.IsRunning()  // 是否运行中 (ready 或 draining 状态)
srv.HealthAddr() // 获取健康检查地址
if err := srv.MarkReady(); err != nil {
    // 非法状态迁移会返回错误,而不是 panic
}

优雅关闭配置:

srv := httpserver.NewServer(&httpserver.Config{
    DrainTimeout:    5 * time.Second,  // 收到关闭信号后等待时间,让负载均衡器切走流量
    ShutdownTimeout: 10 * time.Second, // http.Server.Shutdown 的超时时间
})

自定义 http.Server 配置:

srv := httpserver.NewServer(cfg, httpserver.WithHTTPServerMutator(func(s *http.Server) {
    s.MaxHeaderBytes = 1 << 20
}))

通用中间件:

srv.Use(middleware.Recovery())
srv.Use(middleware.Timeout(2 * time.Second))

可观测性扩展:

prometheus.Register(public, prometheus.Config{Path: "/metrics"})
srv.Use(otel.Middleware(otel.Config{TracerName: "user-service"}))

官方默认装配:

srv := preset.NewProductionServer(nil)

Swagger 集成:

import (
    _ "your/module/internal/docs"

    httpswagger "github.com/tsopia/go-kit/httpserver/swagger"
)

public := srv.Group("")
httpswagger.Register(public, httpswagger.Config{})

更多信息请参考 README.md、httpserver/swagger/README.md 和 docs/httpserver.md

Index

Constants

This section is empty.

Variables

View Source
var ErrInvalidConfig = errors.New("invalid config")

ErrInvalidConfig 表示服务器配置不合法。

Functions

func CORSMiddleware

func CORSMiddleware() gin.HandlerFunc

CORSMiddleware CORS 中间件

func ComposeDecoder added in v1.3.0

func ComposeDecoder[Req any](decoders ...func(*gin.Context, *Req) error) func(*gin.Context, *Req) error

ComposeDecoder 顺序执行多个 decoder。

func ContextFromGin

func ContextFromGin(c *gin.Context) context.Context

ContextFromGin 从 Gin Context 提取 request context 这个 context 包含了 trace_id 和 request_id,可以用于创建 logger 示例用法:

ctx := httpserver.ContextFromGin(c)
logger := logger.FromContext(ctx)
logger.Info("处理用户请求") // 自动包含 trace_id 和 request_id

func DecodeForm added in v1.4.0

func DecodeForm[Req any]() func(*gin.Context, *Req) error

DecodeForm 使用 Gin 的 ShouldBind 填充请求对象(支持 JSON/Form/Multipart 自动识别)。

func DecodeHeader added in v1.4.0

func DecodeHeader[Req any]() func(*gin.Context, *Req) error

DecodeHeader 使用 Header 填充请求对象。

func DecodeJSON added in v1.3.0

func DecodeJSON[Req any]() func(*gin.Context, *Req) error

DecodeJSON 使用 JSON body 填充请求对象。

func DecodeQuery added in v1.3.0

func DecodeQuery[Req any]() func(*gin.Context, *Req) error

DecodeQuery 使用 query string 填充请求对象。

func DecodeURI added in v1.3.0

func DecodeURI[Req any]() func(*gin.Context, *Req) error

DecodeURI 使用 URI 参数填充请求对象。

func DefaultHealthHandler added in v1.0.2

func DefaultHealthHandler() gin.HandlerFunc

DefaultHealthHandler 默认健康检查处理器

func GetRequestID

func GetRequestID(c *gin.Context) string

GetRequestID 从 context 中获取 request id

func GetTraceID

func GetTraceID(c *gin.Context) string

GetTraceID 从 context 中获取 trace id

func Handle added in v1.3.0

func Handle[Req any, Resp any](fn HandlerFunc[Req, Resp], opts ...HandlerOption) gin.HandlerFunc

Handle 将强类型业务函数适配成通用 HTTP handler。

func HandleForm added in v1.4.0

func HandleForm[Req any, Resp any](fn HandlerFunc[Req, Resp], opts ...HandlerOption) gin.HandlerFunc

HandleForm 将强类型业务函数适配成 form handler。 使用 Gin 的 ShouldBind,支持 JSON/Form/Multipart 自动识别。

func HandleJSON added in v1.3.0

func HandleJSON[Req any, Resp any](fn HandlerFunc[Req, Resp], opts ...HandlerOption) gin.HandlerFunc

HandleJSON 将强类型业务函数适配成 JSON HTTP handler。

func HandleNoContent added in v1.4.0

func HandleNoContent[Req any](fn ActionFunc[Req], opts ...HandlerOption) gin.HandlerFunc

HandleNoContent 将无响应体业务函数适配成 HTTP handler(默认 204)。

func HandleQuery added in v1.4.0

func HandleQuery[Req any, Resp any](fn HandlerFunc[Req, Resp], opts ...HandlerOption) gin.HandlerFunc

HandleQuery 将强类型业务函数适配成 query string handler。

func HandleQueryURI added in v1.4.0

func HandleQueryURI[Req any, Resp any](fn HandlerFunc[Req, Resp], opts ...HandlerOption) gin.HandlerFunc

HandleQueryURI 将强类型业务函数适配成 URI + query 组合解码 handler。

func HandleURI added in v1.4.0

func HandleURI[Req any, Resp any](fn HandlerFunc[Req, Resp], opts ...HandlerOption) gin.HandlerFunc

HandleURI 将强类型业务函数适配成 URI 参数 handler。

func HealthHandlerWithManager added in v1.0.2

func HealthHandlerWithManager(manager *HealthCheckManager) gin.HandlerFunc

HealthHandlerWithManager 带管理器的健康检查处理器

func RealIPMiddleware added in v1.4.0

func RealIPMiddleware() gin.HandlerFunc

RealIPMiddleware 可信客户端 IP 解析中间件 默认配置:不信任任何代理,直接使用 RemoteAddr

func RealIPMiddlewareWithConfig added in v1.4.0

func RealIPMiddlewareWithConfig(config httpmiddleware.RealIPConfig) gin.HandlerFunc

RealIPMiddlewareWithConfig 使用自定义配置的 RealIP 中间件

func RequestIDMiddleware

func RequestIDMiddleware() gin.HandlerFunc

RequestIDMiddleware 添加 Request ID 的中间件(每个请求唯一)

func TraceIDMiddleware

func TraceIDMiddleware() gin.HandlerFunc

TraceIDMiddleware 添加 Trace ID 的中间件

Types

type ActionFunc added in v1.4.0

type ActionFunc[Req any] func(ctx context.Context, req Req) error

ActionFunc 描述无响应体的业务处理函数。

type Config

type Config struct {
	Host              string
	Port              int
	ReadTimeout       time.Duration
	ReadHeaderTimeout time.Duration
	WriteTimeout      time.Duration
	IdleTimeout       time.Duration
	MaxHeaderBytes    int
	ShutdownTimeout   time.Duration
	DrainTimeout      time.Duration

	EnableHealthCheck bool
	HealthCheckPath   string
	ReadinessPath     string
	LivenessPath      string
	HealthCheckPort   int
}

Config 服务器配置。

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig 返回默认配置。

func (*Config) Normalize added in v1.4.0

func (c *Config) Normalize()

Normalize 为零值填充默认配置。

func (*Config) Validate added in v1.4.0

func (c *Config) Validate() error

Validate 校验服务器配置。

type CustomHealthChecker added in v1.0.2

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

CustomHealthChecker 自定义健康检查器

func NewCustomHealthChecker added in v1.0.2

func NewCustomHealthChecker(name string, checker func(ctx context.Context) error) *CustomHealthChecker

NewCustomHealthChecker 创建自定义健康检查器

func (*CustomHealthChecker) CheckHealth added in v1.0.2

func (chc *CustomHealthChecker) CheckHealth(ctx context.Context) error

CheckHealth 执行自定义健康检查

func (*CustomHealthChecker) GetName added in v1.0.2

func (chc *CustomHealthChecker) GetName() string

GetName 获取检查器名称

type DatabaseHealthChecker added in v1.0.2

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

DatabaseHealthChecker 数据库健康检查器

func NewDatabaseHealthChecker added in v1.0.2

func NewDatabaseHealthChecker(name string, db interface {
	Ping() error
}) *DatabaseHealthChecker

NewDatabaseHealthChecker 创建数据库健康检查器

func (*DatabaseHealthChecker) CheckHealth added in v1.0.2

func (dhc *DatabaseHealthChecker) CheckHealth(ctx context.Context) error

CheckHealth 检查数据库健康状态

func (*DatabaseHealthChecker) GetName added in v1.0.2

func (dhc *DatabaseHealthChecker) GetName() string

GetName 获取检查器名称

type ErrorMapper added in v1.3.0

type ErrorMapper func(err error) (status int, body any)

ErrorMapper 负责把业务错误映射成 HTTP 响应。

type ErrorResponse added in v1.4.0

type ErrorResponse struct {
	Code    string         `json:"code"`
	Message string         `json:"message"`
	Details map[string]any `json:"details,omitempty"`
}

ErrorResponse 描述 typed handler 的默认错误响应结构。

type HTTPError added in v1.4.0

type HTTPError interface {
	error
	StatusCode() int
	ErrorCode() string
	ErrorMessage() string
	ErrorDetails() map[string]any
}

HTTPError 描述带有 HTTP 语义的业务错误。

type HTTPHealthChecker added in v1.0.2

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

HTTPHealthChecker HTTP服务健康检查器

func NewHTTPHealthChecker added in v1.0.2

func NewHTTPHealthChecker(name, url string, timeout time.Duration) *HTTPHealthChecker

NewHTTPHealthChecker 创建HTTP服务健康检查器

func (*HTTPHealthChecker) CheckHealth added in v1.0.2

func (hhc *HTTPHealthChecker) CheckHealth(ctx context.Context) (err error)

CheckHealth 检查HTTP服务健康状态

func (*HTTPHealthChecker) GetName added in v1.0.2

func (hhc *HTTPHealthChecker) GetName() string

GetName 获取检查器名称

type HTTPServerMutator added in v1.4.0

type HTTPServerMutator func(*http.Server)

HTTPServerMutator 是修改 http.Server 的函数类型。

type HandlerFunc added in v1.3.0

type HandlerFunc[Req any, Resp any] func(ctx context.Context, req Req) (Resp, error)

HandlerFunc 描述强类型请求的业务处理函数。

type HandlerOption added in v1.3.0

type HandlerOption func(*handlerConfig)

HandlerOption 描述 handler 的可选配置。

func WithDecoder added in v1.3.0

func WithDecoder[Req any](decoder func(*gin.Context, *Req) error) HandlerOption

WithDecoder 覆盖默认请求解码器。

func WithEncoder added in v1.3.0

func WithEncoder(encoder func(*gin.Context, int, any)) HandlerOption

WithEncoder 覆盖成功响应编码器。

func WithErrorMapper added in v1.3.0

func WithErrorMapper(mapper ErrorMapper) HandlerOption

WithErrorMapper 为业务错误提供自定义映射。

func WithSuccessStatus added in v1.3.0

func WithSuccessStatus(status int) HandlerOption

WithSuccessStatus 覆盖成功响应状态码。

func WithValidators added in v1.4.0

func WithValidators[Req any](validators ...RequestValidator[Req]) HandlerOption

WithValidators 为 typed handler 追加显式请求校验器。

type HealthCheckManager added in v1.0.2

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

HealthCheckManager 健康检查管理器

func NewHealthCheckManager added in v1.0.2

func NewHealthCheckManager(version string, opts ...HealthCheckOption) *HealthCheckManager

NewHealthCheckManager 创建健康检查管理器

func (*HealthCheckManager) AddChecker added in v1.0.2

func (hcm *HealthCheckManager) AddChecker(checker HealthChecker)

AddChecker 添加健康检查器

func (*HealthCheckManager) CheckHealth added in v1.0.2

func (hcm *HealthCheckManager) CheckHealth(ctx context.Context) *HealthStatus

CheckHealth 并发执行所有健康检查

type HealthCheckOption added in v1.4.0

type HealthCheckOption func(*HealthCheckManager)

HealthCheckOption 描述 HealthCheckManager 的可选配置。

func WithCheckTimeout added in v1.4.0

func WithCheckTimeout(timeout time.Duration) HealthCheckOption

WithCheckTimeout 设置单个 checker 的超时时间。

type HealthChecker added in v1.0.2

type HealthChecker interface {
	CheckHealth(ctx context.Context) error
	GetName() string
}

HealthChecker 健康检查器接口

type HealthStatus added in v1.0.2

type HealthStatus struct {
	Status    string                 `json:"status"`            // healthy, unhealthy
	Timestamp int64                  `json:"timestamp"`         // Unix时间戳
	Version   string                 `json:"version,omitempty"` // 应用版本
	Uptime    int64                  `json:"uptime,omitempty"`  // 运行时间(秒)
	Checks    map[string]interface{} `json:"checks,omitempty"`  // 详细检查结果
	Error     string                 `json:"error,omitempty"`   // 错误信息
}

HealthStatus 健康检查状态

type Hooks added in v1.3.0

type Hooks struct {
	OnStarting         func(context.Context, LifecycleEvent)
	OnStarted          func(context.Context, LifecycleEvent)
	OnServeError       func(context.Context, LifecycleEvent)
	OnShuttingDown     func(context.Context, LifecycleEvent)
	OnShutdownComplete func(context.Context, LifecycleEvent)
	// OnStateChange 在每次状态转换完成后同步调用。
	// 调用时状态机锁已释放,可安全读取服务器状态。
	// 注意:hook 会阻塞当前调用链,请确保其快速返回;
	// 如需异步处理,请在 hook 内部自行开启 goroutine。
	OnStateChange func(ctx context.Context, from State, to State)
}

Hooks 描述服务器生命周期的可选回调。

type LifecycleEvent added in v1.3.0

type LifecycleEvent struct {
	Addr       string
	HealthAddr string
	Err        error
}

LifecycleEvent 描述服务器生命周期事件。

type Option added in v1.3.0

type Option func(*Server)

Option 描述 Server 的可选配置项。

func WithHTTPServerMutator added in v1.4.0

func WithHTTPServerMutator(mutator HTTPServerMutator) Option

WithHTTPServerMutator 注册一个在 http.Server 创建后、启动前调用的 mutator。 用于需要修改底层 http.Server 高级配置的场景。

func WithHooks added in v1.3.0

func WithHooks(h Hooks) Option

WithHooks 为服务器注入生命周期 hooks。

func WithManualReadiness added in v1.4.0

func WithManualReadiness() Option

WithManualReadiness 禁用自动 ready 切换。

func WithModules added in v1.3.0

func WithModules(modules ...RouteModule) Option

WithModules 在构造时批量注册路由模块。

type RequestValidator added in v1.4.0

type RequestValidator[Req any] func(context.Context, Req) error

RequestValidator 描述 typed handler 的显式请求校验器。

type RouteModule added in v1.3.0

type RouteModule interface {
	RegisterRoutes(r gin.IRoutes)
}

RouteModule 描述一组可注册到 Gin 路由树的模块。

type Server

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

Server HTTP服务器 - 最小化封装

func NewServer

func NewServer(config *Config, opts ...Option) *Server

NewServer 创建新的HTTP服务器

func (*Server) Addr

func (s *Server) Addr() string

Addr 返回服务器地址

func (*Server) Any

func (s *Server) Any(relativePath string, handlers ...gin.HandlerFunc)

Any 注册所有HTTP方法的便利方法

func (*Server) DELETE

func (s *Server) DELETE(relativePath string, handlers ...gin.HandlerFunc)

DELETE 注册DELETE路由的便利方法

func (*Server) EnableHealthCheck added in v1.0.2

func (s *Server) EnableHealthCheck()

EnableHealthCheck 启用健康检查并注册默认健康检查路由。

func (*Server) EnableHealthCheckWithManager added in v1.0.2

func (s *Server) EnableHealthCheckWithManager(manager *HealthCheckManager)

EnableHealthCheckWithManager 启用带管理器的健康检查并注册探针路由。

func (*Server) Engine

func (s *Server) Engine() *gin.Engine

Engine 返回Gin引擎,用户完全控制

func (*Server) Errors added in v1.3.0

func (s *Server) Errors() <-chan error

Errors 返回服务器运行期错误通道。

func (*Server) GET

func (s *Server) GET(relativePath string, handlers ...gin.HandlerFunc)

GET 注册GET路由的便利方法

func (*Server) GetHealthCheckPath added in v1.0.2

func (s *Server) GetHealthCheckPath() string

GetHealthCheckPath 获取健康检查路径

func (*Server) Group

func (s *Server) Group(relativePath string, handlers ...gin.HandlerFunc) *gin.RouterGroup

Group 创建路由组的便利方法

func (*Server) HEAD

func (s *Server) HEAD(relativePath string, handlers ...gin.HandlerFunc)

HEAD 注册HEAD路由的便利方法

func (*Server) HealthAddr added in v1.4.0

func (s *Server) HealthAddr() string

HealthAddr 返回健康检查服务器地址。 如果健康检查未启用,返回空字符串。 如果健康检查使用独立端口,返回独立地址;否则返回主服务器地址。

func (*Server) IsRunning

func (s *Server) IsRunning() bool

IsRunning 检查服务器是否正在运行 基于 State() 判断:Ready 或 Draining 状态时返回 true

func (*Server) MarkDraining added in v1.4.0

func (s *Server) MarkDraining() error

MarkDraining 将服务器标记为排空中。

func (*Server) MarkReady added in v1.4.0

func (s *Server) MarkReady() error

MarkReady 将服务器标记为可接流量。

func (*Server) OPTIONS

func (s *Server) OPTIONS(relativePath string, handlers ...gin.HandlerFunc)

OPTIONS 注册OPTIONS路由的便利方法

func (*Server) PATCH

func (s *Server) PATCH(relativePath string, handlers ...gin.HandlerFunc)

PATCH 注册PATCH路由的便利方法

func (*Server) POST

func (s *Server) POST(relativePath string, handlers ...gin.HandlerFunc)

POST 注册POST路由的便利方法

func (*Server) PUT

func (s *Server) PUT(relativePath string, handlers ...gin.HandlerFunc)

PUT 注册PUT路由的便利方法

func (*Server) RegisterModules added in v1.3.0

func (s *Server) RegisterModules(modules ...RouteModule)

RegisterModules 批量注册路由模块。

func (*Server) RegisterRoutes

func (s *Server) RegisterRoutes(routes func(r *gin.Engine))

RegisterRoutes 使用回调函数注册路由(推荐方式)

func (*Server) Run

func (s *Server) Run() error

Run 启动服务器(阻塞)

func (*Server) RunTLS

func (s *Server) RunTLS(certFile, keyFile string) error

RunTLS 启动HTTPS服务器(阻塞)

func (*Server) RunWithContext added in v1.4.0

func (s *Server) RunWithContext(ctx context.Context) error

RunWithContext 启动服务器,当 ctx 取消时自动优雅关闭(阻塞)。 适用于 errgroup 等并发控制场景。

func (*Server) RunWithGracefulShutdown

func (s *Server) RunWithGracefulShutdown() error

RunWithGracefulShutdown 启动服务器并自动处理优雅关闭(阻塞)

func (*Server) Serve added in v1.3.0

func (s *Server) Serve(ln net.Listener) error

Serve 使用现成的 listener 启动服务器(阻塞)。

func (*Server) SetHealthCheckPath added in v1.0.2

func (s *Server) SetHealthCheckPath(path string) error

SetHealthCheckPath 设置健康检查路径。 必须在健康检查路由注册或服务器启动前调用,否则返回错误。

func (*Server) Shutdown

func (s *Server) Shutdown(ctx context.Context) error

Shutdown 优雅关闭服务器

func (*Server) Start

func (s *Server) Start() error

Start 启动服务器(非阻塞)

func (*Server) State added in v1.4.0

func (s *Server) State() State

State 返回当前服务器状态。

func (*Server) Use

func (s *Server) Use(middleware ...gin.HandlerFunc)

Use 添加中间件的便利方法

func (*Server) WaitForShutdown

func (s *Server) WaitForShutdown() error

WaitForShutdown 等待关闭信号并执行优雅关闭

type State added in v1.4.0

type State string

State 描述服务器生命周期状态。

const (
	StateNew      State = "new"
	StateStarting State = "starting"
	StateReady    State = "ready"
	StateDraining State = "draining"
	StateStopping State = "stopping"
	StateStopped  State = "stopped"
	StateFailed   State = "failed"
)

type ValidationError added in v1.4.0

type ValidationError struct {
	Message string            `json:"message"`
	Fields  []ValidationField `json:"fields,omitempty"`
}

ValidationError 描述结构化请求校验错误。

func (*ValidationError) Error added in v1.4.0

func (e *ValidationError) Error() string

type ValidationField added in v1.4.0

type ValidationField struct {
	Field   string `json:"field"`
	Code    string `json:"code,omitempty"`
	Message string `json:"message"`
}

ValidationField 描述字段级校验错误。

Directories

Path Synopsis
integration
errorsx
Package errorsx 提供 errors 包与 httpserver typed handler 之间的桥接映射。
Package errorsx 提供 errors 包与 httpserver typed handler 之间的桥接映射。
Package middleware 提供可复用的 HTTP 中间件集合。
Package middleware 提供可复用的 HTTP 中间件集合。
observability
otel
Package otel 提供 HTTP tracing 中间件。
Package otel 提供 HTTP tracing 中间件。
prometheus
Package prometheus 提供 HTTP 指标中间件与 metrics 路由注册能力。
Package prometheus 提供 HTTP 指标中间件与 metrics 路由注册能力。
Package preset 提供官方推荐的 HTTP server 默认装配。
Package preset 提供官方推荐的 HTTP server 默认装配。
Package swagger 提供 Swagger UI 的 Gin 路由挂载能力。
Package swagger 提供 Swagger UI 的 Gin 路由挂载能力。

Jump to

Keyboard shortcuts

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