Documentation
¶
Overview ¶
Application scenarios: - Record operator, resource, action, and outcome for business-sensitive endpoints. - Provide a stable audit trail for compliance, troubleshooting, and risk control. - Reuse request identity, locale, and security context in a single audit record.
适用场景: - 为业务敏感接口记录操作者、资源、动作和结果。 - 为审计合规、问题排查和风控分析提供稳定审计链路。 - 在同一条审计记录中复用请求标识、语言环境和安全上下文。
Application scenarios: - Protect authenticated routes with a unified authorization layer. - Reuse JWT subject and role information in route-level access control. - Build higher-level permission checks on top of a simple transport middleware contract.
适用场景: - 用统一鉴权层保护需要登录态的路由。 - 在路由级访问控制中复用 JWT 的主体和角色信息。 - 基于简洁的传输层中间件契约构建更高层的权限判断。
Application scenarios: - Capture request and response payload samples for debugging, auditing, and risk-control workflows. - Inspect HTTP exchanges without forcing all business code to implement custom logging. - Keep request-response capture explicit and bounded to reduce privacy and performance risk.
适用场景: - 为调试、审计和风控流程捕获请求与响应样本。 - 在不要求业务代码自行实现自定义日志的前提下观测 HTTP 交换内容。 - 通过显式且有边界的方式进行请求响应捕获,降低隐私和性能风险。
Application scenarios: - Prevent oversized request bodies from consuming too much memory or bandwidth. - Protect upload, callback, and external API endpoints from abusive payloads. - Provide a simple server-side request size guardrail.
适用场景: - 防止超大请求体占用过多内存或网络带宽。 - 保护上传、回调和对外 API 接口免受恶意大包冲击。 - 提供简单直接的服务端请求体大小护栏。
Application scenarios: - Bridge the transport HTTP contract onto Gin without leaking Gin details into mainline middleware. - Keep request context, request object, and response helpers synchronized between transport and Gin. - Support unified middleware behavior while still allowing Gin-specific escape hatches.
适用场景: - 在不把 Gin 细节泄漏到主线中间件的前提下,将 transport HTTP 契约桥接到 Gin。 - 在 transport 与 Gin 之间同步 request context、request 对象和响应助手。 - 在保持统一中间件行为的同时,保留必要的 Gin 专属下沉能力。
Application scenarios: - Add cache directives to read-heavy HTTP APIs. - Avoid re-sending unchanged payloads when the client already has the current entity. - Build a lightweight conditional-request layer for REST-style endpoints.
适用场景: - 为读多写少的 HTTP API 添加缓存指令。 - 当客户端已持有最新实体时避免重复发送未变更内容。 - 为 REST 风格接口建立轻量级条件请求层。
Application scenarios: - Stop unhealthy routes from continuously receiving traffic after repeated failures. - Fail fast on known-bad routes or dependencies and protect the rest of the service. - Align HTTP protection behavior with the framework's unified circuit-breaker capability.
适用场景: - 在连续失败后阻止不健康路由继续接收流量。 - 对已知异常路由或依赖快速失败,保护其余服务能力。 - 让 HTTP 保护行为与框架统一熔断能力保持一致。
Application scenarios: - Reduce response payload size for JSON, text, and similar content. - Improve bandwidth efficiency for external HTTP APIs. - Add a simple, transparent response compression layer for clients that support gzip.
适用场景: - 压缩 JSON、文本等响应内容,减少返回体积。 - 提升对外 HTTP API 的带宽利用效率。 - 为支持 gzip 的客户端提供简单透明的响应压缩层。
Application scenarios: - Limit instantaneous in-flight requests on hot endpoints. - Shed excess traffic early when the service is already overloaded. - Build a lightweight overload-protection baseline without external dependencies.
适用场景: - 限制热点接口的瞬时在途请求数。 - 在服务已经过载时尽早丢弃多余流量。 - 在不依赖外部组件的前提下建立轻量级过载保护基线。
Package middleware provides HTTP health check endpoints for gorp framework. Supports /healthz, /readyz, and /livez endpoints with dependency aggregation.
提供 HTTP 健康检查端点中间件,支持 /healthz、/readyz 和 /livez 端点。
Application scenarios: - Prevent duplicate writes caused by retries, refreshes, or client-side resubmission. - Replay successful write responses for the same idempotency key within a TTL window. - Provide a stable request de-duplication baseline for create, update, and callback endpoints.
适用场景: - 防止重试、刷新或客户端重复提交造成重复写入。 - 在 TTL 窗口内对相同幂等键回放成功写请求的响应。 - 为创建、更新和回调类接口提供稳定的请求去重基线。
Application scenarios: - Restrict internal admin routes to office, bastion, or intranet IP ranges. - Block known abusive or disallowed client segments before business logic runs. - Protect callback and management endpoints with a simple IP policy.
适用场景: - 将内网管理路由限制在办公网、堡垒机或内网 IP 段内。 - 在业务逻辑执行前拦截已知风险或不允许的客户端网段。 - 通过简单 IP 策略保护回调接口和管理接口。
Application scenarios: - Record HTTP access logs with stable request fields. - Reuse request-scoped logger context in downstream business code. - Provide a default request logging baseline for production services.
适用场景: - 记录带有稳定请求字段的 HTTP 访问日志。 - 在下游业务代码中复用请求级 logger 上下文。 - 为生产服务提供默认的请求日志基线。
Application scenarios: - Collect baseline request count and latency metrics for HTTP routes. - Export simple per-method / per-path / per-status observability signals. - Provide a low-cost metrics baseline before adding custom business metrics.
适用场景: - 为 HTTP 路由采集基础请求量和耗时指标。 - 输出按 method / path / status 维度聚合的观测信号。 - 在接入业务自定义指标前,先提供低成本的通用指标基线。
Application scenarios: - Add unified request identity to every HTTP request. - Expose request_id and trace_id to downstream handlers, logs, and responders. - Provide a stable request identity source for idempotency, audit, and tracing correlation.
适用场景: - 为每一个 HTTP 请求补齐统一请求标识。 - 向下游处理器、日志和响应输出暴露 request_id 与 trace_id。 - 为幂等、审计和链路追踪关联提供稳定的请求身份来源。
Package middleware provides the default MiddlewareRegistry implementation. The registry maps named middleware instances (e.g., "auth", "logging") to transportcontract.Middleware, enabling proto-annotation-driven automatic mounting.
本包提供默认的 MiddlewareRegistry 实现。 注册表将具名中间件实例(如 "auth"、"logging")映射到 transportcontract.Middleware,支持 proto 注解驱动的自动挂载。
Application scenarios: - Provide stable default middleware bundles for public, internal, and admin HTTP APIs. - Give business code a simple assembly entry without manually sorting middleware order. - Keep recommended middleware ordering and defaults centralized in one place.
适用场景: - 为对外、内网和管理 HTTP API 提供稳定的默认中间件组合。 - 让业务侧无需手工排序中间件,也能直接完成装配。 - 将推荐顺序与默认值集中维护在一个主线入口中。
Application scenarios: - Protect external APIs from high-frequency bursts. - Apply route-level or resource-level request quotas. - Combine with identity or IP extraction to build access policies.
适用场景: - 保护对外 API,避免高频突发流量冲击。 - 对路由级或资源级请求配额进行控制。 - 结合身份或 IP 提取逻辑构建访问策略。
Application scenarios: - Prevent a single panic from crashing the whole HTTP process. - Convert panic output into the framework's unified error response. - Keep panic records observable in request logs.
适用场景: - 防止单次 panic 直接打垮整个 HTTP 进程。 - 把 panic 转换为框架统一错误响应。 - 让 panic 记录仍然能在请求日志中被观测到。
Application scenarios: - Standardize HTTP success and error output across middleware and handlers. - Keep framework-level business error codes separate from raw HTTP status codes. - Provide reusable responder helpers for common transport-layer response scenarios.
适用场景: - 在中间件与处理器之间统一 HTTP 成功与失败输出。 - 将框架级业务错误码与原始 HTTP 状态码分离。 - 为常见传输层响应场景提供可复用的 responder 助手。
Application scenarios: - Apply a middleware only to selected paths, methods, or route groups. - Build concise route-level governance rules without copying middleware code. - Compose middleware selection logic with Any / All / Not helpers.
适用场景: - 仅对指定路径、方法或路由组生效某个中间件。 - 在不复制中间件代码的前提下构建精简的路由治理规则。 - 用 Any / All / Not 组合复杂的中间件匹配逻辑。
Application scenarios: - Resolve tenant identity from route params, headers, or query parameters for multi-tenant APIs. - Propagate tenant information through request context for downstream business code and middleware. - Enforce required tenant presence at the HTTP mainline boundary.
适用场景: - 为多租户 API 从路由参数、请求头或查询参数中解析租户标识。 - 通过请求上下文把租户信息传递给下游业务代码和中间件。 - 在 HTTP 主线边界强制要求租户信息存在。
Application scenarios: - Stop long-running HTTP requests from occupying request resources forever. - Return a unified timeout response to upstream callers. - Provide a request deadline source for downstream business code.
适用场景: - 阻止长时间运行的 HTTP 请求长期占用请求资源。 - 为上游调用方返回统一的超时响应。 - 为下游业务代码提供请求 deadline 来源。
Application scenarios: - Bind and validate request bodies, query parameters, and form payloads with a unified flow. - Return stable validation error responses to HTTP callers. - Store validated request objects back into request context for downstream reuse.
适用场景: - 以统一流程绑定并校验请求体、查询参数和表单载荷。 - 向 HTTP 调用方返回稳定的参数校验错误响应。 - 将已校验的请求对象回写到请求上下文,供下游复用。
Index ¶
- Constants
- Variables
- func AdminAPIMiddleware(base observabilitycontract.Logger, opts AdminMiddlewareOptions) transportcontract.Middleware
- func AdminAPIMiddlewareSet(base observabilitycontract.Logger, opts AdminMiddlewareOptions) []transportcontract.Middleware
- func AuditMiddleware(base observabilitycontract.Logger, opts AuditOptions) transportcontract.Middleware
- func Authorize(checker AuthorizationChecker) transportcontract.Middleware
- func BadRequest(c transportcontract.Context, message string)
- func BindAndValidate(c transportcontract.Context, validator datacontract.Validator, obj any) error
- func BindAndValidateJSON(c transportcontract.Context, validator datacontract.Validator, obj any) error
- func BindAndValidateQuery(c transportcontract.Context, validator datacontract.Validator, obj any) error
- func BodyDump(opts BodyDumpOptions) transportcontract.Middleware
- func BodyLimit(maxBytes int64) transportcontract.Middleware
- func CORS(opts CORSOptions) transportcontract.Middleware
- func CSRF(opts CSRFOptions) transportcontract.Middleware
- func CacheControl(value string) transportcontract.Middleware
- func Chain(middleware ...transportcontract.Middleware) transportcontract.Middleware
- func CircuitBreaker(cb resiliencecontract.CircuitBreaker, resource string) transportcontract.Middleware
- func CircuitBreakerFromContainer(container runtimecontract.Container, resource string) transportcontract.Middleware
- func Compression() transportcontract.Middleware
- func ConcurrencyLimit(maxConcurrent int, timeout time.Duration) transportcontract.Middleware
- func DefaultHTTPServiceGovernanceOrder() []string
- func DefaultHTTPServiceGovernancePreset(base observabilitycontract.Logger, opts DefaultHTTPServiceGovernanceOptions) transportcontract.Middleware
- func DefaultHTTPServiceGovernanceSet(base observabilitycontract.Logger, opts DefaultHTTPServiceGovernanceOptions) []transportcontract.Middleware
- func DefaultMiddleware(base observabilitycontract.Logger) transportcontract.Middleware
- func DefaultMiddlewareSet(base observabilitycontract.Logger) []transportcontract.Middleware
- func ETag() transportcontract.Middleware
- func Error(c transportcontract.Context, err error)
- func ErrorWithData(c transportcontract.Context, err error, data any)
- func ErrorWithStatus(c transportcontract.Context, status int, err error)
- func Forbidden(c transportcontract.Context, message string)
- func GenerateIdempotencyKey(userID string, operation string, params string) string
- func GetLocale(c *gin.Context) string
- func GetRequestID(c *gin.Context) string
- func GetTenant(c *gin.Context) string
- func GetTraceID(c *gin.Context) string
- func HealthCheckHandler(checker observabilitycontract.HealthChecker) transportcontract.Handler
- func HealthCheckHandlerFromContainer(container runtimecontract.Container) transportcontract.Handler
- func IPAllowlist(allowed ...string) transportcontract.Middleware
- func IPDenylist(denied ...string) transportcontract.Middleware
- func IPKeyFunc(c *gin.Context) string
- func Idempotency(store IdempotencyStore, ttl time.Duration) transportcontract.Middleware
- func IdempotencyKeyFromRequest(c *gin.Context, userID string) string
- func IdempotencyMiddleware(store IdempotencyStore, ttl time.Duration) gin.HandlerFunc
- func InternalAPIMiddleware(base observabilitycontract.Logger, opts InternalMiddlewareOptions) transportcontract.Middleware
- func InternalAPIMiddlewareSet(base observabilitycontract.Logger, opts InternalMiddlewareOptions) []transportcontract.Middleware
- func InternalError(c transportcontract.Context, message string)
- func IsRequestCanceled(c *gin.Context) bool
- func LivenessHandler() transportcontract.Handler
- func LoadShedding(maxConcurrent int) transportcontract.Middleware
- func LoadSheddingFromContainer(container runtimecontract.Container, resource string) transportcontract.Middleware
- func Locale(opts LocaleOptions) transportcontract.Middleware
- func LoggingMiddleware(base observabilitycontract.Logger) transportcontract.Middleware
- func MetricsMiddleware() transportcontract.Middleware
- func NewDefaultResponder() transportcontract.HTTPResponder
- func NewMiddlewareRegistry() transportcontract.MiddlewareRegistry
- func NewTestEngine() *gin.Engine
- func NotFound(c transportcontract.Context, message string)
- func RateLimit(limiter resiliencecontract.RateLimiter, resource string) transportcontract.Middleware
- func RateLimitFromContainer(container runtimecontract.Container, resource string) transportcontract.Middleware
- func RateLimitMiddleware(limiter RateLimiter, keyFunc func(*gin.Context) string) gin.HandlerFunc
- func ReadinessHandler(checker observabilitycontract.HealthChecker) transportcontract.Handler
- func ReadinessHandlerFromContainer(container runtimecontract.Container) transportcontract.Handler
- func RecommendedAPIMiddleware(base observabilitycontract.Logger, opts RecommendedMiddlewareOptions) transportcontract.Middleware
- func RecommendedAPIMiddlewareSet(base observabilitycontract.Logger, opts RecommendedMiddlewareOptions) []transportcontract.Middleware
- func RecoveryMiddleware() transportcontract.Middleware
- func RegisterHealthEndpoints(router transportcontract.Router, container runtimecontract.Container)
- func RegisterHealthEndpointsSimple(router transportcontract.Router, serviceName, version string)
- func RequestIdentity() transportcontract.Middleware
- func RequestTimeout(c *gin.Context) time.Duration
- func RequireAllRoles(roles ...string) transportcontract.Middleware
- func RequireAnyRole(roles ...string) transportcontract.Middleware
- func RequireAuthorization() transportcontract.Middleware
- func RequireSubjectType(subjectTypes ...string) transportcontract.Middleware
- func SecurityHeaders(opts SecurityHeadersOptions) transportcontract.Middleware
- func SetTrustedProxies(cidrs []string)
- func Success(c transportcontract.Context, data any)
- func SuccessPaginated(c transportcontract.Context, items any, total int64, page, pageSize int)
- func SuccessWithMessage(c transportcontract.Context, message string, data any)
- func SuccessWithStatus(c transportcontract.Context, status int, data any)
- func Tenant(opts TenantOptions) transportcontract.Middleware
- func Timeout(timeout time.Duration) transportcontract.Middleware
- func TimeoutMiddleware(timeout time.Duration) gin.HandlerFunc
- func TimeoutMiddlewareWithHandler(timeout time.Duration, onTimeout func(*gin.Context)) gin.HandlerFunc
- func Unauthorized(c transportcontract.Context, message string)
- func UseAdminAPIMiddleware(router transportcontract.Router, base observabilitycontract.Logger, ...)
- func UseDefaultHTTPServiceGovernance(router transportcontract.Router, base observabilitycontract.Logger, ...)
- func UseDefaultMiddleware(router transportcontract.Router, base observabilitycontract.Logger)
- func UseInternalAPIMiddleware(router transportcontract.Router, base observabilitycontract.Logger, ...)
- func UseRecommendedAPIMiddleware(router transportcontract.Router, base observabilitycontract.Logger, ...)
- func ValidateBodyMiddleware(validator datacontract.Validator, prototype any) func(*gin.Context)
- func ValidateQueryMiddleware(validator datacontract.Validator, prototype any) func(*gin.Context)
- func When(predicate HTTPPredicate, middleware transportcontract.Middleware) transportcontract.Middleware
- type AdminMiddlewareOptions
- type AuditOptions
- type AuthorizationChecker
- type BizError
- func ErrBadRequest(message string) *BizError
- func ErrForbidden(message string) *BizError
- func ErrInternal(message string) *BizError
- func ErrNotFound(message string) *BizError
- func ErrOrderNotFound() *BizError
- func ErrOutOfStock() *BizError
- func ErrProductNotFound() *BizError
- func ErrUnauthorized(message string) *BizError
- func ErrUserNotFound() *BizError
- func NewBizError(code int, message string) *BizError
- type BodyDumpOptions
- type BusinessError
- type CORSOptions
- type CSRFOptions
- type ConcurrencyLimiter
- type DefaultHTTPServiceGovernanceOptions
- type DefaultResponder
- func (DefaultResponder) BadRequest(c transportcontract.Context, message string)
- func (DefaultResponder) Error(c transportcontract.Context, err error)
- func (DefaultResponder) InternalError(c transportcontract.Context, message string)
- func (DefaultResponder) Success(c transportcontract.Context, data any)
- func (DefaultResponder) SuccessWithMessage(c transportcontract.Context, message string, data any)
- func (DefaultResponder) SuccessWithStatus(c transportcontract.Context, status int, data any)
- type FixedWindowLimiter
- type HTTPExchangeCapture
- type HTTPPredicate
- type HealthCheckEndpoint
- type IdempotencyResponse
- type IdempotencyStore
- type InternalMiddlewareOptions
- type LocaleOptions
- type MemoryIdempotencyStore
- type PaginatedData
- type RateLimiter
- type RecommendedMiddlewareOptions
- type Response
- type SecurityHeadersOptions
- type SlidingWindowLimiter
- type TenantOptions
- type TokenBucketLimiter
- type ValidateErrorResponse
Constants ¶
const ( CodeSuccess = 0 CodeBadRequest = 1001 CodeForbidden = 1003 CodeNotFound = 1004 CodeInternalError = 1005 CodeTooManyRequests = 1007 CodeConflict = 1008 CodeValidationFailed = 1009 CodeUserNotFound = 10001 CodeUserAlreadyExists = 10002 CodeUserPasswordWrong = 10003 CodeUserDisabled = 10004 CodeUserTokenExpired = 10005 CodeUserTokenInvalid = 10006 CodeOrderNotFound = 20001 CodeOrderStatusInvalid = 20002 CodeOrderAlreadyPaid = 20003 CodeOrderCanceled = 20004 CodeProductNotFound = 30001 CodeProductOutOfStock = 30002 CodeProductDisabled = 30003 CodePaymentFailed = 40001 CodePaymentTimeout = 40002 CodePaymentCanceled = 40003 )
const ( // IdempotencyKeyHeader is the standard request header used to carry the idempotency key. // // IdempotencyKeyHeader 是用于传递幂等键的标准请求头。 IdempotencyKeyHeader = "X-Idempotency-Key" )
Variables ¶
var DefaultResponderInstance transportcontract.HTTPResponder = DefaultResponder{}
DefaultResponderInstance is the shared default responder singleton.
DefaultResponderInstance 是共享的默认 responder 单例。
var DefaultSensitiveHeaders = map[string]struct{}{
"authorization": {},
"cookie": {},
"x-csrf-token": {},
"x-xsrf-token": {},
"proxy-authorization": {},
"www-authenticate": {},
}
DefaultSensitiveHeaders is the default list of sensitive header keys that are excluded from capture to avoid leaking credentials and security tokens.
DefaultSensitiveHeaders 是默认的敏感头键列表,捕获时排除以避免泄露凭证和安全令牌。
Functions ¶
func AdminAPIMiddleware ¶
func AdminAPIMiddleware(base observabilitycontract.Logger, opts AdminMiddlewareOptions) transportcontract.Middleware
AdminAPIMiddleware returns the recommended admin API middleware preset.
AdminAPIMiddleware 返回推荐的管理 API 中间件预设。
func AdminAPIMiddlewareSet ¶
func AdminAPIMiddlewareSet(base observabilitycontract.Logger, opts AdminMiddlewareOptions) []transportcontract.Middleware
AdminAPIMiddlewareSet returns the recommended admin API middleware preset as an ordered slice.
AdminAPIMiddlewareSet 以有序切片形式返回推荐的管理 API 中间件预设。
Included middleware: - InternalAPIMiddlewareSet - IPAllowlist, when configured - RequireAuthorization, when enabled - RequireAnyRole, when configured - RequireAllRoles, when configured - AuditMiddleware, when enabled
包含的中间件: - InternalAPIMiddlewareSet - 配置后追加 IPAllowlist - 启用时追加 RequireAuthorization - 配置后追加 RequireAnyRole - 配置后追加 RequireAllRoles - 启用时追加 AuditMiddleware
func AuditMiddleware ¶
func AuditMiddleware(base observabilitycontract.Logger, opts AuditOptions) transportcontract.Middleware
AuditMiddleware writes a structured audit log for the current HTTP request.
AuditMiddleware 为当前 HTTP 请求输出结构化审计日志。
Example:
router.Use(httpmiddleware.AuditMiddleware(logger, httpmiddleware.AuditOptions{}))
func Authorize ¶
func Authorize(checker AuthorizationChecker) transportcontract.Middleware
Authorize enforces JWT claim presence first, then applies the custom checker.
Authorize 先校验 JWT claims 是否存在,再执行自定义鉴权逻辑。
func BadRequest ¶
func BadRequest(c transportcontract.Context, message string)
BadRequest writes a standard bad-request response.
BadRequest 输出标准的错误请求响应。
func BindAndValidate ¶
func BindAndValidate(c transportcontract.Context, validator datacontract.Validator, obj any) error
BindAndValidate binds a generic request payload and validates the bound object.
BindAndValidate 绑定通用请求载荷并校验绑定后的对象。
func BindAndValidateJSON ¶
func BindAndValidateJSON(c transportcontract.Context, validator datacontract.Validator, obj any) error
BindAndValidateJSON binds a JSON payload and validates the bound object.
BindAndValidateJSON 绑定 JSON 载荷并校验绑定后的对象。
func BindAndValidateQuery ¶
func BindAndValidateQuery(c transportcontract.Context, validator datacontract.Validator, obj any) error
BindAndValidateQuery binds query parameters and validates the bound object.
BindAndValidateQuery 绑定查询参数并校验绑定后的对象。
func BodyDump ¶
func BodyDump(opts BodyDumpOptions) transportcontract.Middleware
BodyDump captures request-response exchange details and forwards them to the configured callback.
BodyDump 捕获请求响应交换细节,并转发给配置的回调。
Example:
router.Use(httpmiddleware.BodyDump(httpmiddleware.BodyDumpOptions{
CaptureRequestBody: true,
CaptureResponseBody: true,
MaxBodyBytes: 4096,
OnCapture: func(ctx gorp.Context, dump *httpmiddleware.HTTPExchangeCapture) {
// consume captured exchange
},
}))
func BodyLimit ¶
func BodyLimit(maxBytes int64) transportcontract.Middleware
BodyLimit constrains the incoming request body size for the HTTP mainline.
BodyLimit 为 HTTP 主线限制请求体大小。
func CORS ¶
func CORS(opts CORSOptions) transportcontract.Middleware
CORS applies cross-origin resource sharing headers to the HTTP mainline.
CORS 为 HTTP 主线应用跨域响应头。
func CSRF ¶
func CSRF(opts CSRFOptions) transportcontract.Middleware
CSRF 创建 CSRF 防护中间件。
中文说明: - 对安全方法(GET/HEAD/OPTIONS/TRACE)只设置 cookie,不校验 token; - 对非安全方法(POST/PUT/PATCH/DELETE)校验请求头或表单中的 token; - token 不匹配时返回 403 Forbidden; - 适用场景:传统的 cookie-based 会话 + 表单提交的 Web 应用; - 对于纯 API 服务(JWT / Bearer Token 认证),通常不需要 CSRF 防护。
func CacheControl ¶
func CacheControl(value string) transportcontract.Middleware
CacheControl writes a fixed Cache-Control header for the current response.
CacheControl 为当前响应写入固定的 Cache-Control 头。
func Chain ¶
func Chain(middleware ...transportcontract.Middleware) transportcontract.Middleware
Chain combines multiple middlewares into a single middleware.
Chain 将多个中间件组合成一个中间件。
func CircuitBreaker ¶
func CircuitBreaker(cb resiliencecontract.CircuitBreaker, resource string) transportcontract.Middleware
CircuitBreaker protects HTTP requests with the configured circuit breaker.
CircuitBreaker 使用给定的熔断器保护 HTTP 请求。
使用方式:
cb, _ := container.Make[resiliencecontract.CircuitBreaker](c, resiliencecontract.CircuitBreakerKey) router.Use(middleware.CircuitBreaker(cb, "external-api"))
func CircuitBreakerFromContainer ¶
func CircuitBreakerFromContainer(container runtimecontract.Container, resource string) transportcontract.Middleware
CircuitBreakerFromContainer 自动从容器获取熔断器并应用熔断中间件。 无需手动从容器获取 circuit breaker,直接使用即可。
使用方式:
router.Use(middleware.CircuitBreakerFromContainer(container, "external-api"))
如果容器中未注册 CircuitBreaker,中间件会静默跳过(不报错)。
func Compression ¶
func Compression() transportcontract.Middleware
Compression enables gzip response compression for clients that support it.
Compression 为支持 gzip 的客户端开启响应压缩。
func ConcurrencyLimit ¶
func ConcurrencyLimit(maxConcurrent int, timeout time.Duration) transportcontract.Middleware
ConcurrencyLimit waits for a free slot until timeout, then rejects the request.
ConcurrencyLimit 在超时前等待空闲槽位,超时后拒绝请求。
func DefaultHTTPServiceGovernanceOrder ¶
func DefaultHTTPServiceGovernanceOrder() []string
DefaultHTTPServiceGovernanceOrder returns the stable logical order of the HTTP server governance middleware chain.
The order here defines the formal execution contract: middleware registered earlier wraps all later middleware, so it runs first on the inbound path and last on the outbound path. Any change to this list is a breaking change to the governance chain contract.
DefaultHTTPServiceGovernanceOrder 返回 HTTP 服务端治理中间件链的稳定逻辑顺序。
此顺序定义了正式的执行契约:先注册的中间件包裹后注册的所有中间件, 因此在入站路径上最先执行、在出站路径上最后执行。 对本列表的任何变更都是治理链契约的破坏性变更。
func DefaultHTTPServiceGovernancePreset ¶
func DefaultHTTPServiceGovernancePreset(base observabilitycontract.Logger, opts DefaultHTTPServiceGovernanceOptions) transportcontract.Middleware
DefaultHTTPServiceGovernancePreset returns the default HTTP service governance middleware preset.
DefaultHTTPServiceGovernancePreset 返回默认 HTTP 服务治理中间件预设。
func DefaultHTTPServiceGovernanceSet ¶
func DefaultHTTPServiceGovernanceSet(base observabilitycontract.Logger, opts DefaultHTTPServiceGovernanceOptions) []transportcontract.Middleware
DefaultHTTPServiceGovernanceSet returns the default HTTP service governance preset as an ordered slice.
DefaultHTTPServiceGovernanceSet 以有序切片形式返回默认 HTTP 服务治理预设。
Included middleware: - DefaultMiddlewareSet - CORS, when configured - SecurityHeaders, when enabled - Timeout, when configured - LoadShedding, when MaxConcurrent > 0 - RateLimit, when a limiter is provided - CircuitBreaker, when a breaker is provided - BodyLimit, when configured - Locale, when enabled - MetricsMiddleware, when enabled - Compression, when enabled
包含的中间件: - DefaultMiddlewareSet - 配置后追加 CORS - 启用时追加 SecurityHeaders - 配置后追加 Timeout - MaxConcurrent 大于 0 时追加 LoadShedding - 提供 limiter 时追加 RateLimit - 提供 breaker 时追加 CircuitBreaker - 配置后追加 BodyLimit - 启用时追加 Locale - 启用时追加 MetricsMiddleware - 启用时追加 Compression
func DefaultMiddleware ¶
func DefaultMiddleware(base observabilitycontract.Logger) transportcontract.Middleware
DefaultMiddleware returns the stable default middleware baseline.
DefaultMiddleware 返回稳定的默认中间件基线。
func DefaultMiddlewareSet ¶
func DefaultMiddlewareSet(base observabilitycontract.Logger) []transportcontract.Middleware
DefaultMiddlewareSet returns the stable default middleware baseline as an ordered slice.
DefaultMiddlewareSet 以有序切片形式返回稳定的默认中间件基线。
Included middleware: - RequestIdentity - LoggingMiddleware - RecoveryMiddleware
包含的中间件: - RequestIdentity - LoggingMiddleware - RecoveryMiddleware
func ETag ¶
func ETag() transportcontract.Middleware
ETag computes a weak ETag for successful GET/HEAD responses and handles If-None-Match.
ETag 为成功的 GET/HEAD 响应计算弱 ETag,并处理 If-None-Match。
func Error ¶
func Error(c transportcontract.Context, err error)
Error writes an error response using the default responder.
Error 使用默认 responder 输出错误响应。
func ErrorWithData ¶
func ErrorWithData(c transportcontract.Context, err error, data any)
ErrorWithData writes an error response and attaches extra response data.
ErrorWithData 输出错误响应,并附带额外数据。
func ErrorWithStatus ¶
func ErrorWithStatus(c transportcontract.Context, status int, err error)
ErrorWithStatus writes an error response using a caller-provided HTTP status.
ErrorWithStatus 使用调用方指定的 HTTP 状态码输出错误响应。
func Forbidden ¶
func Forbidden(c transportcontract.Context, message string)
Forbidden writes a standard forbidden response.
Forbidden 输出标准的无权限响应。
func GenerateIdempotencyKey ¶
GenerateIdempotencyKey derives a stable idempotency key from business dimensions.
GenerateIdempotencyKey 根据业务维度生成稳定的幂等键。
func GetLocale ¶
GetLocale reads the negotiated locale from a Gin request context.
GetLocale 从 Gin 请求上下文中读取协商后的 locale。
func GetRequestID ¶
GetRequestID reads the request id from a Gin request context.
GetRequestID 从 Gin 请求上下文中读取 request id。
func GetTenant ¶
GetTenant reads the resolved tenant identity from a Gin request context.
GetTenant 从 Gin 请求上下文中读取已解析的租户标识。
func GetTraceID ¶
GetTraceID reads the trace id from a Gin request context.
GetTraceID 从 Gin 请求上下文中读取 trace id。
func HealthCheckHandler ¶
func HealthCheckHandler(checker observabilitycontract.HealthChecker) transportcontract.Handler
HealthCheckHandler 创建健康检查 HTTP handler。 返回聚合的健康报告,包含所有组件和依赖的状态。
使用方式:
checker, _ := container.Make(observabilitycontract.HealthCheckerKey)
router.GET("/healthz", middleware.HealthCheckHandler(checker))
func HealthCheckHandlerFromContainer ¶
func HealthCheckHandlerFromContainer(container runtimecontract.Container) transportcontract.Handler
HealthCheckHandlerFromContainer 从容器获取健康检查器并创建 handler。
使用方式:
router.GET("/healthz", middleware.HealthCheckHandlerFromContainer(container))
func IPAllowlist ¶
func IPAllowlist(allowed ...string) transportcontract.Middleware
IPAllowlist allows only requests whose client IP matches the configured entries.
IPAllowlist 仅允许客户端 IP 命中配置项的请求继续执行。
func IPDenylist ¶
func IPDenylist(denied ...string) transportcontract.Middleware
IPDenylist rejects requests whose client IP matches the configured entries.
IPDenylist 拒绝客户端 IP 命中配置项的请求。
func IPKeyFunc ¶
IPKeyFunc extracts a client-IP-based rate-limit key from the request. X-Forwarded-For and X-Real-IP headers are ONLY trusted when the request originates from a trusted proxy (see SetTrustedProxies in ip_filter.go). Otherwise, RemoteAddr is used directly to prevent spoofing.
IPKeyFunc 从请求中提取基于客户端 IP 的限流 key。 X-Forwarded-For 和 X-Real-IP 头仅在请求来自可信代理时才会被信任 (见 ip_filter.go 中的 SetTrustedProxies)。 否则直接使用 RemoteAddr,以防止伪造绕过限流。
func Idempotency ¶
func Idempotency(store IdempotencyStore, ttl time.Duration) transportcontract.Middleware
Idempotency applies request de-duplication to transport-level HTTP middleware.
Idempotency 将请求去重能力应用到 transport 层 HTTP 中间件链。
func IdempotencyKeyFromRequest ¶
IdempotencyKeyFromRequest reads the request idempotency key or derives one from trace context.
IdempotencyKeyFromRequest 读取请求幂等键,或根据链路上下文派生一个幂等键。
func IdempotencyMiddleware ¶
func IdempotencyMiddleware(store IdempotencyStore, ttl time.Duration) gin.HandlerFunc
IdempotencyMiddleware is the native Gin form of the idempotency middleware.
IdempotencyMiddleware 是幂等中间件的原生 Gin 形态。
Example:
router.Use(httpmiddleware.IdempotencyMiddleware(store, time.Hour))
func InternalAPIMiddleware ¶
func InternalAPIMiddleware(base observabilitycontract.Logger, opts InternalMiddlewareOptions) transportcontract.Middleware
InternalAPIMiddleware returns the recommended internal API middleware preset.
InternalAPIMiddleware 返回推荐的内网 API 中间件预设。
func InternalAPIMiddlewareSet ¶
func InternalAPIMiddlewareSet(base observabilitycontract.Logger, opts InternalMiddlewareOptions) []transportcontract.Middleware
InternalAPIMiddlewareSet returns the recommended internal API middleware preset as an ordered slice.
InternalAPIMiddlewareSet 以有序切片形式返回推荐的内网 API 中间件预设。
Included middleware: - RecommendedAPIMiddlewareSet after internal defaults are applied
包含的中间件: - 应用内网默认配置后的 RecommendedAPIMiddlewareSet
func InternalError ¶
func InternalError(c transportcontract.Context, message string)
InternalError writes a standard internal-error response.
InternalError 输出标准的内部错误响应。
func IsRequestCanceled ¶
IsRequestCanceled reports whether the current request context has been canceled.
IsRequestCanceled 判断当前请求上下文是否已经取消。
func LivenessHandler ¶
func LivenessHandler() transportcontract.Handler
LivenessHandler 创建存活检查 HTTP handler。 用于 Kubernetes liveness probe,检查服务是否存活。 如果服务能响应,就认为存活。
使用方式:
router.GET("/livez", middleware.LivenessHandler())
func LoadShedding ¶
func LoadShedding(maxConcurrent int) transportcontract.Middleware
LoadShedding rejects the request immediately when the concurrency limit is full. 优先使用容器中的 LoadShedder 契约实现;若容器不可用则回退到本地 ConcurrencyLimiter。
LoadShedding 在并发已满时立即拒绝请求。 优先使用容器中的 LoadShedder 契约实现;若容器不可用则回退到本地 ConcurrencyLimiter。
使用方式:
router.Use(middleware.LoadShedding(500)) // 最大并发 500
func LoadSheddingFromContainer ¶
func LoadSheddingFromContainer(container runtimecontract.Container, resource string) transportcontract.Middleware
LoadSheddingFromContainer 自动从容器获取过载保护器并应用过载保护中间件。 无需手动从容器获取 shedder,直接使用即可。
使用方式:
router.Use(middleware.LoadSheddingFromContainer(container, "api"))
如果容器中未注册 LoadShedder,中间件会静默跳过(不报错)。
func Locale ¶
func Locale(opts LocaleOptions) transportcontract.Middleware
Locale negotiates the request locale and stores it in the request context.
Locale 协商请求语言,并将结果写入请求上下文。
func LoggingMiddleware ¶
func LoggingMiddleware(base observabilitycontract.Logger) transportcontract.Middleware
LoggingMiddleware writes a request-scoped access log and stores the derived logger in context.
LoggingMiddleware 输出请求级访问日志,并把派生后的 logger 写回上下文。
Example:
router.Use(httpmiddleware.LoggingMiddleware(logger))
func MetricsMiddleware ¶
func MetricsMiddleware() transportcontract.Middleware
MetricsMiddleware records basic HTTP request metrics for the current request.
MetricsMiddleware 为当前请求记录基础 HTTP 指标。
func NewDefaultResponder ¶
func NewDefaultResponder() transportcontract.HTTPResponder
NewDefaultResponder returns the shared default HTTP responder.
NewDefaultResponder 返回共享的默认 HTTP responder。
func NewMiddlewareRegistry ¶
func NewMiddlewareRegistry() transportcontract.MiddlewareRegistry
NewMiddlewareRegistry creates a new empty middleware registry.
NewMiddlewareRegistry 创建一个新的空中间件注册表。
func NewTestEngine ¶ added in v0.1.2
NewTestEngine creates a gin.Engine configured for testing with ContextWithFallback enabled. This ensures gin.Context.Value() properly delegates to Request.Context().Value() for non-string keys, which is required for context.Context value propagation.
NewTestEngine 创建用于测试的 gin.Engine,启用 ContextWithFallback。 确保 gin.Context.Value() 正确委托到 Request.Context().Value() 处理非字符串 key, 这是 context.Context 值传播的必要设置。
Example:
engine := NewTestEngine()
engine.Use(YourMiddleware())
engine.GET("/test", handler)
func NotFound ¶
func NotFound(c transportcontract.Context, message string)
NotFound writes a standard not-found response.
NotFound 输出标准的资源不存在响应。
func RateLimit ¶
func RateLimit(limiter resiliencecontract.RateLimiter, resource string) transportcontract.Middleware
RateLimit applies a transport-level rate limiter and returns a unified 429 response when exceeded.
RateLimit 应用 transport 层限流器,并在超限时返回统一的 429 响应。
使用方式:
limiter, _ := container.Make[resiliencecontract.RateLimiter](c, resiliencecontract.RateLimiterKey) router.Use(middleware.RateLimit(limiter, "api"))
func RateLimitFromContainer ¶
func RateLimitFromContainer(container runtimecontract.Container, resource string) transportcontract.Middleware
RateLimitFromContainer 自动从容器获取限流器并应用限流中间件。 无需手动从容器获取 limiter,直接使用即可。
使用方式:
router.Use(middleware.RateLimitFromContainer(container, "api"))
如果容器中未注册 RateLimiter,中间件会静默跳过(不报错)。
func RateLimitMiddleware ¶
func RateLimitMiddleware(limiter RateLimiter, keyFunc func(*gin.Context) string) gin.HandlerFunc
RateLimitMiddleware is the native Gin form of the rate-limiting middleware.
RateLimitMiddleware 是限流中间件的原生 Gin 形态。
func ReadinessHandler ¶
func ReadinessHandler(checker observabilitycontract.HealthChecker) transportcontract.Handler
ReadinessHandler 创建就绪检查 HTTP handler。 用于 Kubernetes readiness probe,检查服务是否准备好接收流量。 如果任何依赖不健康,返回 503。
使用方式:
router.GET("/readyz", middleware.ReadinessHandler(checker))
func ReadinessHandlerFromContainer ¶
func ReadinessHandlerFromContainer(container runtimecontract.Container) transportcontract.Handler
ReadinessHandlerFromContainer 从容器获取健康检查器并创建就绪检查 handler。
使用方式:
router.GET("/readyz", middleware.ReadinessHandlerFromContainer(container))
func RecommendedAPIMiddleware ¶
func RecommendedAPIMiddleware(base observabilitycontract.Logger, opts RecommendedMiddlewareOptions) transportcontract.Middleware
RecommendedAPIMiddleware returns the recommended public API middleware preset.
RecommendedAPIMiddleware 返回推荐的对外 API 中间件预设。
func RecommendedAPIMiddlewareSet ¶
func RecommendedAPIMiddlewareSet(base observabilitycontract.Logger, opts RecommendedMiddlewareOptions) []transportcontract.Middleware
RecommendedAPIMiddlewareSet returns the recommended public API middleware preset as an ordered slice.
RecommendedAPIMiddlewareSet 以有序切片形式返回推荐的对外 API 中间件预设。
Included middleware: - DefaultMiddlewareSet - CORS, when enabled - SecurityHeaders, when enabled - Timeout, when configured - BodyLimit, when configured - Locale, when enabled - MetricsMiddleware, when enabled - Compression, when enabled
包含的中间件: - DefaultMiddlewareSet - 启用时追加 CORS - 启用时追加 SecurityHeaders - 配置后追加 Timeout - 配置后追加 BodyLimit - 启用时追加 Locale - 启用时追加 MetricsMiddleware - 启用时追加 Compression
func RecoveryMiddleware ¶
func RecoveryMiddleware() transportcontract.Middleware
RecoveryMiddleware recovers panics and returns a unified internal-error response. 包含 stack trace 以便生产环境排查问题。
RecoveryMiddleware 捕获 panic,并返回统一的内部错误响应。 包含 stack trace 以便生产环境排查问题。
func RegisterHealthEndpoints ¶
func RegisterHealthEndpoints(router transportcontract.Router, container runtimecontract.Container)
RegisterHealthEndpoints 注册所有健康检查端点。 包括 /healthz、/readyz 和 /livez。
使用方式:
middleware.RegisterHealthEndpoints(router, container)
func RegisterHealthEndpointsSimple ¶
func RegisterHealthEndpointsSimple(router transportcontract.Router, serviceName, version string)
RegisterHealthEndpointsSimple 注册简单的健康检查端点(不检查依赖)。 适用于单体应用或不需要依赖检查的场景。
使用方式:
middleware.RegisterHealthEndpointsSimple(router, serviceName, version)
func RequestIdentity ¶
func RequestIdentity() transportcontract.Middleware
RequestIdentity injects request_id and trace_id into the current HTTP request context.
RequestIdentity 将 request_id 与 trace_id 注入当前 HTTP 请求上下文。
Example:
router.Use(httpmiddleware.RequestIdentity())
func RequestTimeout ¶
RequestTimeout returns the remaining timeout budget of the current request.
RequestTimeout 返回当前请求剩余的超时预算。
func RequireAllRoles ¶
func RequireAllRoles(roles ...string) transportcontract.Middleware
RequireAllRoles requires the caller to own all expected roles.
RequireAllRoles 要求调用方拥有全部指定角色。
func RequireAnyRole ¶
func RequireAnyRole(roles ...string) transportcontract.Middleware
RequireAnyRole requires the caller to own at least one of the expected roles.
RequireAnyRole 要求调用方至少拥有一个指定角色。
func RequireAuthorization ¶
func RequireAuthorization() transportcontract.Middleware
RequireAuthorization requires authenticated JWT claims to exist in the request context.
RequireAuthorization 要求请求上下文中必须存在已认证的 JWT claims。
func RequireSubjectType ¶
func RequireSubjectType(subjectTypes ...string) transportcontract.Middleware
RequireSubjectType requires the JWT subject type to match one of the expected values.
RequireSubjectType 要求 JWT subject type 命中给定候选值之一。
func SecurityHeaders ¶
func SecurityHeaders(opts SecurityHeadersOptions) transportcontract.Middleware
SecurityHeaders writes a small secure-by-default response header set.
SecurityHeaders 输出一组安全默认响应头。
func SetTrustedProxies ¶
func SetTrustedProxies(cidrs []string)
SetTrustedProxies configures the networks that are considered trusted reverse proxies. Only requests from these networks will have their X-Forwarded-For / X-Real-IP headers honoured by requestClientIP and IPKeyFunc. Pass nil or an empty slice to disable header trust entirely (safest).
SetTrustedProxies 配置被认为是可信反向代理的网络。 仅来自这些网络的请求才会让其 X-Forwarded-For / X-Real-IP 头被 requestClientIP 和 IPKeyFunc 使用。 传入 nil 或空切片可完全禁用头信任(最安全)。
func Success ¶
func Success(c transportcontract.Context, data any)
Success writes a standard success response using the default responder.
Success 使用默认 responder 输出标准成功响应。
func SuccessPaginated ¶
func SuccessPaginated(c transportcontract.Context, items any, total int64, page, pageSize int)
SuccessPaginated writes a standard paginated success response.
SuccessPaginated 输出标准的分页成功响应。
func SuccessWithMessage ¶
func SuccessWithMessage(c transportcontract.Context, message string, data any)
SuccessWithMessage writes a success response with a custom message.
SuccessWithMessage 输出带自定义消息的成功响应。
func SuccessWithStatus ¶
func SuccessWithStatus(c transportcontract.Context, status int, data any)
SuccessWithStatus writes a success response with a custom HTTP status.
SuccessWithStatus 输出带自定义 HTTP 状态码的成功响应。
func Tenant ¶
func Tenant(opts TenantOptions) transportcontract.Middleware
Tenant resolves tenant identity and stores it in request context.
Tenant 解析租户标识并将其写入请求上下文。
Example:
router.Use(httpmiddleware.Tenant(httpmiddleware.DefaultTenantOptions()))
func Timeout ¶
func Timeout(timeout time.Duration) transportcontract.Middleware
Timeout enforces a request deadline on the transport-level HTTP middleware chain.
Timeout 在 transport 层 HTTP 中间件链上施加请求超时约束。
func TimeoutMiddleware ¶
func TimeoutMiddleware(timeout time.Duration) gin.HandlerFunc
TimeoutMiddleware is the native Gin timeout middleware form.
TimeoutMiddleware 是超时中间件的原生 Gin 形态。
func TimeoutMiddlewareWithHandler ¶
func TimeoutMiddlewareWithHandler(timeout time.Duration, onTimeout func(*gin.Context)) gin.HandlerFunc
TimeoutMiddlewareWithHandler applies a timeout and delegates timeout output to a custom callback.
TimeoutMiddlewareWithHandler 应用超时控制,并把超时后的输出交给自定义回调处理。
func Unauthorized ¶
func Unauthorized(c transportcontract.Context, message string)
Unauthorized writes a standard unauthorized response.
Unauthorized 输出标准的未认证响应。
func UseAdminAPIMiddleware ¶
func UseAdminAPIMiddleware(router transportcontract.Router, base observabilitycontract.Logger, opts AdminMiddlewareOptions)
UseAdminAPIMiddleware applies the recommended admin API middleware preset to the router.
UseAdminAPIMiddleware 将推荐的管理 API 中间件预设装配到路由器。
func UseDefaultHTTPServiceGovernance ¶
func UseDefaultHTTPServiceGovernance(router transportcontract.Router, base observabilitycontract.Logger, opts DefaultHTTPServiceGovernanceOptions)
UseDefaultHTTPServiceGovernance applies the default HTTP service governance preset to the router.
UseDefaultHTTPServiceGovernance 将默认 HTTP 服务治理预设装配到路由器。
func UseDefaultMiddleware ¶
func UseDefaultMiddleware(router transportcontract.Router, base observabilitycontract.Logger)
UseDefaultMiddleware applies the default middleware baseline to the router.
UseDefaultMiddleware 将默认中间件基线装配到路由器。
func UseInternalAPIMiddleware ¶
func UseInternalAPIMiddleware(router transportcontract.Router, base observabilitycontract.Logger, opts InternalMiddlewareOptions)
UseInternalAPIMiddleware applies the recommended internal API middleware preset to the router.
UseInternalAPIMiddleware 将推荐的内网 API 中间件预设装配到路由器。
func UseRecommendedAPIMiddleware ¶
func UseRecommendedAPIMiddleware(router transportcontract.Router, base observabilitycontract.Logger, opts RecommendedMiddlewareOptions)
UseRecommendedAPIMiddleware applies the recommended public API middleware preset to the router.
UseRecommendedAPIMiddleware 将推荐的对外 API 中间件预设装配到路由器。
func ValidateBodyMiddleware ¶
func ValidateBodyMiddleware(validator datacontract.Validator, prototype any) func(*gin.Context)
ValidateBodyMiddleware creates a Gin middleware that automatically binds and validates the JSON request body into the given prototype object. The prototype must be a pointer to a struct; each request gets a new zero-value copy. On bind failure or validation failure, the middleware writes a unified error response and aborts. On success, the validated object is stored in request context for downstream retrieval.
ValidateBodyMiddleware 创建自动绑定并校验 JSON 请求体的 Gin 中间件。 prototype 必须是结构体指针;每次请求会创建一个新的零值拷贝。 绑定或校验失败时,中间件输出统一错误响应并中断请求链。 校验成功后,已校验对象存入请求上下文供下游复用。
Example:
type CreateUserReq struct {
Name string `json:"name" validate:"required,min=3"`
Email string `json:"email" validate:"required,email"`
}
router.POST("/users", httpmiddleware.ValidateBodyMiddleware(validator, &CreateUserReq{}), createUserHandler)
func ValidateQueryMiddleware ¶
func ValidateQueryMiddleware(validator datacontract.Validator, prototype any) func(*gin.Context)
ValidateQueryMiddleware creates a Gin middleware that automatically binds and validates query parameters into the given prototype object. The prototype must be a pointer to a struct; each request gets a new zero-value copy. On bind failure or validation failure, the middleware writes a unified error response and aborts. On success, the validated object is stored in request context for downstream retrieval.
ValidateQueryMiddleware 创建自动绑定并校验查询参数的 Gin 中间件。 prototype 必须是结构体指针;每次请求会创建一个新的零值拷贝。 绑定或校验失败时,中间件输出统一错误响应并中断请求链。 校验成功后,已校验对象存入请求上下文供下游复用。
func When ¶
func When(predicate HTTPPredicate, middleware transportcontract.Middleware) transportcontract.Middleware
When applies the wrapped middleware only when the predicate matches.
When 仅在谓词命中时应用被包装的中间件。
Types ¶
type AdminMiddlewareOptions ¶
type AdminMiddlewareOptions struct {
API RecommendedMiddlewareOptions
Allowlist []string
EnableAudit bool
DisableAudit bool
AuditOptions AuditOptions
RequireAuthorization bool
DisableAuthorization bool
RequireAnyRoles []string
RequireAllRoles []string
}
AdminMiddlewareOptions controls the admin API middleware bundle.
AdminMiddlewareOptions 用于控制管理 API 中间件组合。
func DefaultAdminMiddlewareOptions ¶
func DefaultAdminMiddlewareOptions() AdminMiddlewareOptions
DefaultAdminMiddlewareOptions returns the default admin API options.
DefaultAdminMiddlewareOptions 返回管理 API 的默认配置。
type AuditOptions ¶
type AuditOptions struct {
Event string
Action func(transportcontract.Context) string
Resource func(transportcontract.Context) string
Skip func(transportcontract.Context) bool
}
AuditOptions controls request-level audit logging behavior.
AuditOptions 用于控制请求级审计日志的输出行为。
type AuthorizationChecker ¶
type AuthorizationChecker func(c transportcontract.Context, claims *securitycontract.JWTClaims) error
AuthorizationChecker performs a request-level authorization decision.
AuthorizationChecker 用于执行请求级鉴权判断。
type BizError ¶
type BizError struct {
// contains filtered or unexported fields
}
BizError is the default framework business error implementation.
BizError 是框架默认的业务错误实现。
func ErrOrderNotFound ¶
func ErrOrderNotFound() *BizError
ErrOrderNotFound creates the standard order-not-found business error.
ErrOrderNotFound 创建标准的订单不存在业务错误。
func ErrOutOfStock ¶
func ErrOutOfStock() *BizError
ErrOutOfStock creates the standard out-of-stock business error.
ErrOutOfStock 创建标准的库存不足业务错误。
func ErrProductNotFound ¶
func ErrProductNotFound() *BizError
ErrProductNotFound creates the standard product-not-found business error.
ErrProductNotFound 创建标准的商品不存在业务错误。
func ErrUnauthorized ¶
ErrUnauthorized creates an unauthorized business error.
ErrUnauthorized 创建未认证业务错误。
func ErrUserNotFound ¶
func ErrUserNotFound() *BizError
ErrUserNotFound creates the standard user-not-found business error.
ErrUserNotFound 创建标准的用户不存在业务错误。
func NewBizError ¶
NewBizError creates a new business error with the given code and message.
NewBizError 使用给定错误码和消息创建业务错误。
type BodyDumpOptions ¶
type BodyDumpOptions struct {
CaptureRequestHeaders bool
CaptureResponseHeaders bool
CaptureRequestBody bool
CaptureResponseBody bool
MaxBodyBytes int
// SensitiveHeaders is a set of header keys (case-insensitive) to exclude from capture.
// If nil, DefaultSensitiveHeaders is used. Set to an empty map to capture all headers.
//
// SensitiveHeaders 是捕获时要排除的头部键集合(大小写不敏感)。
// 若为 nil 则使用 DefaultSensitiveHeaders。设为空 map 可捕获所有头部。
SensitiveHeaders map[string]struct{}
Skip func(transportcontract.Context) bool
OnCapture func(transportcontract.Context, *HTTPExchangeCapture)
}
BodyDumpOptions controls request-response capture behavior.
BodyDumpOptions 控制请求响应捕获行为。
type BusinessError ¶
BusinessError describes an error carrying framework business code and message semantics.
BusinessError 描述带有框架业务错误码与消息语义的错误。
type CORSOptions ¶
type CORSOptions struct {
AllowOrigins []string
AllowMethods []string
AllowHeaders []string
ExposeHeaders []string
AllowCredentials bool
MaxAgeSeconds int
}
CORSOptions defines the CORS behavior of the HTTP middleware.
CORSOptions 定义 HTTP 中间件的跨域行为。
func DefaultCORSOptions ¶
func DefaultCORSOptions() CORSOptions
DefaultCORSOptions returns the default CORS configuration.
DefaultCORSOptions 返回默认的跨域配置。
type CSRFOptions ¶
type CSRFOptions struct {
TokenLength int
HeaderName string
FormFieldName string
CookieName string
CookiePath string
CookieSecure bool
CookieHTTPOnly bool
CookieSameSite http.SameSite
ErrorHandler func(transportcontract.Context)
}
CSRFOptions 定义 CSRF 防护中间件的配置。
中文说明: - TokenLength:生成的 CSRF token 字节数,默认 32; - HeaderName:校验 token 的请求头名称,默认 X-CSRF-Token; - FormFieldName:表单中 token 字段名,默认 csrf_token; - CookieName:存放 token 的 cookie 名称,默认 _csrf; - CookiePath:cookie 路径,默认 /; - CookieSecure:cookie 是否设置 Secure 标志,默认 false(开发环境 HTTP); - CookieHTTPOnly:cookie 是否设置 HttpOnly 标志,默认 false(前端 JS 需读取); - CookieSameSite:cookie SameSite 属性,默认 Lax; - ErrorHandler:自定义错误处理函数,默认返回 403。
func DefaultCSRFOptions ¶
func DefaultCSRFOptions() CSRFOptions
DefaultCSRFOptions 返回 CSRF 中间件的默认配置。
中文说明: - Token 长度 32 字节,通过请求头 X-CSRF-Token 校验; - Cookie 名 _csrf,SameSite=Lax,不设 HttpOnly(前端需读取 token 放入请求头); - 安全方法(GET/HEAD/OPTIONS/TRACE)不校验 token,只设置 cookie。
type ConcurrencyLimiter ¶
type ConcurrencyLimiter struct {
// contains filtered or unexported fields
}
ConcurrencyLimiter is a lightweight semaphore used by HTTP protection middleware.
ConcurrencyLimiter 是 HTTP 保护中间件使用的轻量级信号量。
func NewConcurrencyLimiter ¶
func NewConcurrencyLimiter(maxConcurrent int) *ConcurrencyLimiter
NewConcurrencyLimiter creates a limiter with the given maximum concurrency.
NewConcurrencyLimiter 按给定最大并发数创建一个限制器。
type DefaultHTTPServiceGovernanceOptions ¶
type DefaultHTTPServiceGovernanceOptions struct {
API RecommendedMiddlewareOptions
RateLimiter resiliencecontract.RateLimiter
RateLimitResource string
CircuitBreaker resiliencecontract.CircuitBreaker
CircuitBreakerResource string
MaxConcurrent int
}
DefaultHTTPServiceGovernanceOptions controls the default HTTP service governance preset.
DefaultHTTPServiceGovernanceOptions 用于控制默认 HTTP 服务治理预设。
func DefaultHTTPServiceGovernanceDefaults ¶
func DefaultHTTPServiceGovernanceDefaults() DefaultHTTPServiceGovernanceOptions
DefaultHTTPServiceGovernanceDefaults returns the default HTTP service governance options.
DefaultHTTPServiceGovernanceDefaults 返回默认 HTTP 服务治理选项。
type DefaultResponder ¶
type DefaultResponder struct{}
DefaultResponder is the default HTTP responder implementation.
DefaultResponder 是默认的 HTTP responder 实现。
func (DefaultResponder) BadRequest ¶
func (DefaultResponder) BadRequest(c transportcontract.Context, message string)
func (DefaultResponder) Error ¶
func (DefaultResponder) Error(c transportcontract.Context, err error)
func (DefaultResponder) InternalError ¶
func (DefaultResponder) InternalError(c transportcontract.Context, message string)
func (DefaultResponder) Success ¶
func (DefaultResponder) Success(c transportcontract.Context, data any)
func (DefaultResponder) SuccessWithMessage ¶
func (DefaultResponder) SuccessWithMessage(c transportcontract.Context, message string, data any)
func (DefaultResponder) SuccessWithStatus ¶
func (DefaultResponder) SuccessWithStatus(c transportcontract.Context, status int, data any)
type FixedWindowLimiter ¶
type FixedWindowLimiter struct {
// contains filtered or unexported fields
}
FixedWindowLimiter is an in-memory fixed-window limiter.
FixedWindowLimiter 是一个内存固定窗口限流器。
func NewFixedWindowLimiter ¶
func NewFixedWindowLimiter(limit int, window time.Duration) *FixedWindowLimiter
NewFixedWindowLimiter creates an in-memory fixed-window limiter.
NewFixedWindowLimiter 创建一个内存固定窗口限流器。
func (*FixedWindowLimiter) Allow ¶
func (l *FixedWindowLimiter) Allow(key string) bool
Allow checks whether the key is still within the fixed-window quota.
Allow 判断给定 key 是否仍在固定窗口配额内。
type HTTPExchangeCapture ¶
type HTTPExchangeCapture struct {
Method string
Path string
Route string
Status int
RequestID string
TraceID string
Tenant string
RequestHeaders map[string]string
ResponseHeaders map[string]string
RequestBody []byte
ResponseBody []byte
RequestTruncated bool
ResponseTruncated bool
}
HTTPExchangeCapture describes a captured HTTP request-response exchange.
HTTPExchangeCapture 描述一次被捕获的 HTTP 请求响应交换。
type HTTPPredicate ¶
type HTTPPredicate func(transportcontract.Context) bool
HTTPPredicate decides whether the current middleware should apply to the request.
HTTPPredicate 用于判断当前中间件是否应当作用于该请求。
func All ¶
func All(predicates ...HTTPPredicate) HTTPPredicate
All returns a predicate that matches only when all child predicates match.
All 返回一个“全部子谓词命中才命中”的组合谓词。
func Any ¶
func Any(predicates ...HTTPPredicate) HTTPPredicate
Any returns a predicate that matches when any child predicate matches.
Any 返回一个“任一子谓词命中即命中”的组合谓词。
func MatchMethod ¶
func MatchMethod(method string) HTTPPredicate
MatchMethod creates a predicate that matches an HTTP method.
MatchMethod 创建一个匹配 HTTP 方法的谓词。
func MatchPath ¶
func MatchPath(path string) HTTPPredicate
MatchPath creates a predicate that matches an exact route or URL path.
MatchPath 创建一个匹配精确路由或 URL 路径的谓词。
func MatchPrefix ¶
func MatchPrefix(prefix string) HTTPPredicate
MatchPrefix creates a predicate that matches a path prefix.
MatchPrefix 创建一个匹配路径前缀的谓词。
func Not ¶
func Not(predicate HTTPPredicate) HTTPPredicate
Not returns the negated predicate.
Not 返回一个取反后的谓词。
type HealthCheckEndpoint ¶
type HealthCheckEndpoint struct {
// Path 是健康检查端点路径。
//
// Path 是健康检查端点路径。
Path string
// Checker 是健康检查器。
//
// Checker 是健康检查器。
Checker observabilitycontract.HealthChecker
}
HealthCheckEndpoint 配置健康检查端点。
HealthCheckEndpoint 配置健康检查端点。
type IdempotencyResponse ¶
type IdempotencyResponse struct {
StatusCode int `json:"status_code"`
Body []byte `json:"body,omitempty"`
ContentType string `json:"content_type,omitempty"`
Headers map[string]string `json:"headers,omitempty"`
}
IdempotencyResponse is the cached response payload used for replay.
IdempotencyResponse 表示用于回放的缓存响应内容。
type IdempotencyStore ¶
type IdempotencyStore interface {
// Reserve atomically attempts to reserve the key for processing.
// Returns (false, cachedResponse) if the key already exists — the caller
// should replay cachedResponse to the client.
// Returns (true, nil) if the key was successfully reserved — the caller
// should proceed with processing and then call Commit.
//
// Reserve 原子地尝试预留 key 进行处理。
// 如果 key 已存在则返回 (false, cachedResponse) —— 调用方应回放 cachedResponse。
// 如果 key 成功预留则返回 (true, nil) —— 调用方应继续处理并调用 Commit。
Reserve(key string, ttl time.Duration) (reserved bool, response *IdempotencyResponse)
// Commit stores the final response for a previously reserved key.
//
// Commit 为之前预留的 key 存储最终响应。
Commit(key string, response *IdempotencyResponse, ttl time.Duration)
}
IdempotencyStore stores idempotent responses for later replay. The Reserve/Commit pattern eliminates the TOCTOU race between Check and Set: Reserve atomically reserves a key (preventing duplicate processing) or returns the previously stored response; Commit finalizes the stored response.
IdempotencyStore 用于存储幂等响应,以便后续回放。 Reserve/Commit 模式消除了 Check 和 Set 之间的 TOCTOU 竞态: Reserve 原子地预留一个 key(防止重复处理)或返回已存储的响应; Commit 最终确认存储的响应。
type InternalMiddlewareOptions ¶
type InternalMiddlewareOptions struct {
API RecommendedMiddlewareOptions
}
InternalMiddlewareOptions controls the internal API middleware bundle.
InternalMiddlewareOptions 用于控制内网 API 中间件组合。
func DefaultInternalMiddlewareOptions ¶
func DefaultInternalMiddlewareOptions() InternalMiddlewareOptions
DefaultInternalMiddlewareOptions returns the default internal API options.
DefaultInternalMiddlewareOptions 返回内网 API 的默认配置。
type LocaleOptions ¶
type LocaleOptions struct {
Supported []string
Default string
QueryKeys []string
HeaderKeys []string
WriteHeader bool
}
LocaleOptions controls request-level locale negotiation.
LocaleOptions 控制请求级语言协商行为。
func DefaultLocaleOptions ¶
func DefaultLocaleOptions() LocaleOptions
DefaultLocaleOptions returns the default locale negotiation behavior.
DefaultLocaleOptions 返回默认语言协商配置。
type MemoryIdempotencyStore ¶
type MemoryIdempotencyStore struct {
// contains filtered or unexported fields
}
MemoryIdempotencyStore is an in-memory idempotency response store. Uses sync.Map.LoadOrStore for atomic Reserve, eliminating TOCTOU races.
MemoryIdempotencyStore 是一个内存型幂等响应存储。 使用 sync.Map.LoadOrStore 实现原子 Reserve,消除 TOCTOU 竞态。
func NewMemoryIdempotencyStore ¶
func NewMemoryIdempotencyStore() *MemoryIdempotencyStore
NewMemoryIdempotencyStore creates a memory-backed idempotency store.
NewMemoryIdempotencyStore 创建一个基于内存的幂等存储。
func (*MemoryIdempotencyStore) Close ¶
func (s *MemoryIdempotencyStore) Close()
Close 停止 cleanup goroutine,释放资源。 调用后 store 不应再被使用。
func (*MemoryIdempotencyStore) Commit ¶
func (s *MemoryIdempotencyStore) Commit(key string, response *IdempotencyResponse, ttl time.Duration)
Commit stores the final response for a previously reserved key.
Commit 为之前预留的 key 存储最终响应。
func (*MemoryIdempotencyStore) Reserve ¶
func (s *MemoryIdempotencyStore) Reserve(key string, ttl time.Duration) (bool, *IdempotencyResponse)
Reserve atomically reserves a key or returns the cached response. Uses sync.Map.LoadOrStore to guarantee that only one goroutine wins the reservation for a given key, eliminating TOCTOU races.
Reserve 原子地预留 key 或返回已缓存的响应。 使用 sync.Map.LoadOrStore 保证只有一个 goroutine 赢得给定 key 的预留, 消除 TOCTOU 竞态。
type PaginatedData ¶
type PaginatedData struct {
Items any `json:"items"`
Total int64 `json:"total"`
Page int `json:"page"`
PageSize int `json:"page_size"`
}
PaginatedData is the standard pagination payload shape.
PaginatedData 是标准的分页载荷结构。
type RateLimiter ¶
RateLimiter is the native Gin limiter contract used by RateLimitMiddleware.
RateLimiter 是 RateLimitMiddleware 使用的原生 Gin 限流器契约。
type RecommendedMiddlewareOptions ¶
type RecommendedMiddlewareOptions struct {
EnableMetrics bool
EnableCompression bool
Timeout time.Duration
BodyLimitBytes int64
CORS *CORSOptions
DisableSecurityHeaders bool
SecurityHeaders *SecurityHeadersOptions
DisableLocale bool
Locale *LocaleOptions
}
RecommendedMiddlewareOptions controls the recommended API middleware bundle.
RecommendedMiddlewareOptions 用于控制推荐 API 中间件组合的装配方式。
func DefaultRecommendedMiddlewareOptions ¶
func DefaultRecommendedMiddlewareOptions() RecommendedMiddlewareOptions
DefaultRecommendedMiddlewareOptions returns the default recommended API options.
DefaultRecommendedMiddlewareOptions 返回推荐对外 API 的默认配置。
type Response ¶
type Response struct {
Code int `json:"code"`
Message string `json:"message"`
Data any `json:"data,omitempty"`
}
Response is the standard HTTP response envelope used by the framework.
Response 是框架使用的标准 HTTP 响应包裹结构。
type SecurityHeadersOptions ¶
type SecurityHeadersOptions struct {
XFrameOptions string
XContentTypeOptions string
ReferrerPolicy string
ContentSecurityPolicy string
PermissionsPolicy string
}
SecurityHeadersOptions defines the default HTTP security response headers.
SecurityHeadersOptions 定义默认 HTTP 安全响应头集合。
func DefaultSecurityHeadersOptions ¶
func DefaultSecurityHeadersOptions() SecurityHeadersOptions
DefaultSecurityHeadersOptions returns the default security header set.
DefaultSecurityHeadersOptions 返回默认安全响应头配置。
type SlidingWindowLimiter ¶
type SlidingWindowLimiter struct {
// contains filtered or unexported fields
}
SlidingWindowLimiter is an in-memory sliding-window limiter.
SlidingWindowLimiter 是一个内存滑动窗口限流器。
func NewSlidingWindowLimiter ¶
func NewSlidingWindowLimiter(limit int, window time.Duration) *SlidingWindowLimiter
NewSlidingWindowLimiter creates an in-memory sliding-window limiter.
NewSlidingWindowLimiter 创建一个内存滑动窗口限流器。
func (*SlidingWindowLimiter) Allow ¶
func (l *SlidingWindowLimiter) Allow(key string) bool
Allow checks whether the key is still within the sliding-window quota.
Allow 判断给定 key 是否仍在滑动窗口配额内。
type TenantOptions ¶
type TenantOptions struct {
ParamKeys []string
HeaderKeys []string
QueryKeys []string
Default string
Required bool
WriteHeader bool
HeaderName string
}
TenantOptions controls request-level tenant resolution behavior.
TenantOptions 控制请求级租户解析行为。
func DefaultTenantOptions ¶
func DefaultTenantOptions() TenantOptions
DefaultTenantOptions returns the default tenant resolution behavior.
DefaultTenantOptions 返回默认的租户解析配置。
type TokenBucketLimiter ¶
type TokenBucketLimiter struct {
// contains filtered or unexported fields
}
TokenBucketLimiter is an in-memory token-bucket limiter for lightweight HTTP protection.
TokenBucketLimiter 是一个用于轻量 HTTP 保护的内存令牌桶限流器。
func NewTokenBucketLimiter ¶
func NewTokenBucketLimiter(rate float64, burst int) *TokenBucketLimiter
NewTokenBucketLimiter creates an in-memory token-bucket limiter.
NewTokenBucketLimiter 创建一个内存令牌桶限流器。
func (*TokenBucketLimiter) Allow ¶
func (l *TokenBucketLimiter) Allow(_ string) bool
Allow consumes one token when available and reports whether the request may proceed.
Allow 在令牌可用时消耗一个令牌,并返回请求是否允许继续。
Source Files
¶
- audit.go
- authorization.go
- body_dump.go
- body_limit.go
- bridge_gin.go
- cache.go
- circuit_breaker.go
- compression.go
- concurrency.go
- cors.go
- csrf.go
- health.go
- idempotency.go
- ip_filter.go
- locale.go
- logging.go
- metrics.go
- middleware.go
- middleware_registry.go
- preset.go
- ratelimit.go
- recovery.go
- response.go
- security_headers.go
- selector.go
- tenant.go
- timeout.go
- validate.go