Help us shape the future of Go! Take the 2026 Go Developer Survey

chain

package
v0.12.1 Latest Latest
Warning

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

Go to latest
Published: Oct 28, 2026 License: MIT Imports: 4 Imported by: 0

Documentation

Overview

Package chain 定义 transport 无关的中间件链原语(参照 go-kratos middleware)。

Handler 签名 func(ctx, req any) (any, error) 与 nns-endpoint.Endpoint、 go-kratos Handler 同形:一份中间件(recovery/timeout/访问日志等)即可在 hertz、kitex、nns-endpoint 各形态间经桥接复用。

本包为框架无关的底层契约包:只依赖标准库,不得 import 任何框架或 oekit 模块。

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Handler

type Handler func(ctx context.Context, req any) (any, error)

Handler 是被中间件链调用的处理器。

func Finalize

func Finalize(terminal Handler, m ...Middleware) Handler

Finalize 等价 Chain(m...)(terminal),惯用 sugar。

type Middleware

type Middleware func(Handler) Handler

Middleware 是 transport 无关中间件:包装 next Handler。

func Chain

func Chain(m ...Middleware) Middleware

Chain 把 m 按顺序包在 next 外层:Chain(a, b)(next) == a(b(next))。 空链返回透传。

func Recovery

func Recovery(opts ...RecoveryOption) Middleware

Recovery 返回 panic 恢复中间件:下游 panic 被转换为 *PanicError 返回, 链不中断(调用方拿到 error 而非进程崩溃)。

func Timeout

func Timeout(d time.Duration) Middleware

Timeout 返回超时中间件:为下游派生带 deadline 的 ctx,超时先到即返回 context.DeadlineExceeded。

语义边界:与 go-kratos 相同——若下游 handler 不理会 ctx 取消(阻塞在 不受 ctx 控制的 IO 上),超时返回后其 goroutine 仍在后台运行至自然结束, 本中间件无法强制中断。

type PanicError

type PanicError struct {
	// Value 是 panic 的原始值。
	Value any
	// Stack 是 panic 时的调用栈(debug.Stack)。
	Stack string
}

PanicError 是 Recovery 把下游 panic 转换出的错误。

func (*PanicError) Error

func (e *PanicError) Error() string

type RecoveryOption

type RecoveryOption func(*recoveryConfig)

RecoveryOption 配置 Recovery 中间件。

func WithPanicReporter

func WithPanicReporter(fn func(ctx context.Context, req any, pv PanicError)) RecoveryOption

WithPanicReporter 注入监控上报钩子(transport 无关版;panic 转换为 PanicError 后回调)。hertz 侧对接 Sentry 等可在此桥接。

Jump to

Keyboard shortcuts

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