Documentation
¶
Overview ¶
Package interceptor provides commonly used grpc client-side and server-side interceptors.
Index ¶
- Variables
- func ClientCtxRequestID(ctx context.Context) string
- func ClientCtxRequestIDField(ctx context.Context) logger.Field
- func ClientTokenOption(appID string, appKey string, isSecure bool) grpc.DialOption
- func CtxRequestIDField(ctx context.Context) logger.Field
- func GetAuthCtxKey() string
- func GetAuthorization(token string) string
- func GetJwtClaims(ctx context.Context) (*jwt.Claims, bool)
- func GetJwtCustomClaims(ctx context.Context) (*jwt.CustomClaims, bool)
- func GetUIDByCtx(ctx context.Context) (uid uint64, err error)
- func NewClientStatsHandler() stats.Handler
- func NewServerStatsHandler() stats.Handler
- func ServerCtxRequestID(ctx context.Context) string
- func ServerCtxRequestIDField(ctx context.Context) logger.Field
- func SetAuthToCtx(ctx context.Context, authorization string) context.Context
- func SetContextRequestIDKey(_ string)
- func SetJwtTokenToCtx(ctx context.Context, token string) context.Context
- func StreamClientCircuitBreaker(opts ...CircuitBreakerOption) grpc.StreamClientInterceptor
- func StreamClientLog(opts ...LogOption) grpc.StreamClientInterceptor
- func StreamClientMetrics() grpc.StreamClientInterceptor
- func StreamClientRecovery() grpc.StreamClientInterceptor
- func StreamClientRequestID() grpc.StreamClientInterceptor
- func StreamClientRetry(opts ...RetryOption) grpc.StreamClientInterceptor
- func StreamClientTimeout(d time.Duration) grpc.StreamClientInterceptor
- func StreamClientTracing() grpc.StreamClientInterceptor
- func StreamServerCircuitBreaker(opts ...CircuitBreakerOption) grpc.StreamServerInterceptor
- func StreamServerJwtAuth(opts ...AuthOption) grpc.StreamServerInterceptor
- func StreamServerLog(opts ...LogOption) grpc.StreamServerInterceptor
- func StreamServerMetrics(opts ...metrics.Option) grpc.StreamServerInterceptor
- func StreamServerRateLimit(opts ...RatelimitOption) grpc.StreamServerInterceptor
- func StreamServerRecovery() grpc.StreamServerInterceptor
- func StreamServerRequestID() grpc.StreamServerInterceptor
- func StreamServerSimpleLog(opts ...LogOption) grpc.StreamServerInterceptor
- func StreamServerToken(f CheckToken) grpc.StreamServerInterceptor
- func StreamServerTracing() grpc.StreamServerInterceptor
- func UnaryClientCircuitBreaker(opts ...CircuitBreakerOption) grpc.UnaryClientInterceptor
- func UnaryClientLog(opts ...LogOption) grpc.UnaryClientInterceptor
- func UnaryClientMetrics() grpc.UnaryClientInterceptor
- func UnaryClientRecovery() grpc.UnaryClientInterceptor
- func UnaryClientRequestID() grpc.UnaryClientInterceptor
- func UnaryClientRetry(opts ...RetryOption) grpc.UnaryClientInterceptor
- func UnaryClientTimeout(d time.Duration) grpc.UnaryClientInterceptor
- func UnaryClientTracing() grpc.UnaryClientInterceptor
- func UnaryServerCircuitBreaker(opts ...CircuitBreakerOption) grpc.UnaryServerInterceptor
- func UnaryServerJwtAuth(opts ...AuthOption) grpc.UnaryServerInterceptor
- func UnaryServerLog(opts ...LogOption) grpc.UnaryServerInterceptor
- func UnaryServerMetrics(opts ...metrics.Option) grpc.UnaryServerInterceptor
- func UnaryServerRateLimit(opts ...RatelimitOption) grpc.UnaryServerInterceptor
- func UnaryServerRecovery() grpc.UnaryServerInterceptor
- func UnaryServerRequestID() grpc.UnaryServerInterceptor
- func UnaryServerSimpleLog(opts ...LogOption) grpc.UnaryServerInterceptor
- func UnaryServerToken(f CheckToken) grpc.UnaryServerInterceptor
- func UnaryServerTracing() grpc.UnaryServerInterceptor
- func VerifySignatureInterceptor(opts ...SignOption) grpc.UnaryServerInterceptor
- func WrapServerCtx(ctx context.Context, kvs ...KV) context.Context
- type AuthOption
- type CheckToken
- type CircuitBreakerOption
- type CtxKeyString
- type CustomVerifyFn
- type KV
- type LogOption
- type RatelimitOption
- type RetryOption
- type SignOption
- type StandardVerifyFn
Constants ¶
This section is empty.
Variables ¶
var ErrLimitExceed = rl.ErrLimitExceed
ErrLimitExceed is returned when the rate limiter is triggered and the request is rejected due to limit exceeded.
var ErrNotAllowed = circuitbreaker.ErrNotAllowed
ErrNotAllowed error not allowed.
var RequestIDKey = CtxKeyString(string(logger.ContextKeyRequestID))
RequestIDKey request_id 的上下文键
Functions ¶
func ClientCtxRequestID ¶
ClientCtxRequestID 从 gRPC 客户端 context.Context 中获取 request_id 参数:
- ctx: 上下文对象
返回:
- string: request_id 字符串,如果不存在则返回空字符串
func ClientCtxRequestIDField ¶
ClientCtxRequestIDField 从 gRPC 客户端 context.Context 中获取 request_id 字段(用于日志记录) 参数:
- ctx: 上下文对象
返回:
- logger.Field: 包含 request_id 的日志字段
func ClientTokenOption ¶
func ClientTokenOption(appID string, appKey string, isSecure bool) grpc.DialOption
ClientTokenOption client token
func CtxRequestIDField ¶
CtxRequestIDField 从 context.Context 中获取 request_id 字段(用于日志记录) 参数:
- ctx: 上下文对象
返回:
- logger.Field: 包含 request_id 的日志字段
func GetAuthorization ¶
GetAuthorization combining tokens into authentication information
func GetJwtClaims ¶ added in v1.0.49
GetJwtClaims get the jwt standard claims from context, contains fixed fields uid and name
func GetJwtCustomClaims ¶ added in v1.0.49
func GetJwtCustomClaims(ctx context.Context) (*jwt.CustomClaims, bool)
GetJwtCustomClaims get the jwt custom claims from context, contains custom fields
func GetUIDByCtx ¶ added in v1.4.27
GetUIDByCtx 从 Context 中获取用户ID
func NewClientStatsHandler ¶ added in v1.4.18
NewClientStatsHandler returns a new client-side stats handler for tracing
func NewServerStatsHandler ¶ added in v1.4.18
NewServerStatsHandler returns a new server-side stats handler for tracing
func ServerCtxRequestID ¶
ServerCtxRequestID 从 gRPC 服务端 context.Context 中获取 request_id 参数:
- ctx: 上下文对象
返回:
- string: request_id 字符串,从 incoming metadata 中提取,如果不存在则返回空字符串
func ServerCtxRequestIDField ¶
ServerCtxRequestIDField 从 gRPC 服务端 context.Context 中获取 request_id 字段(用于日志记录) 参数:
- ctx: 上下文对象
返回:
- logger.Field: 包含 request_id 的日志字段
func SetAuthToCtx ¶ added in v1.0.49
SetAuthToCtx set the authorization (including prefix Bearer) to the context in grpc client side Example:
ctx := SetAuthToCtx(ctx, authorization) cli.GetByID(ctx, req)
func SetContextRequestIDKey ¶
func SetContextRequestIDKey(_ string)
SetContextRequestIDKey 设置上下文 request_id 的键(已废弃) Deprecated: 此函数仅为向后兼容而保留,请直接使用 logger.ContextKeyRequestID
func SetJwtTokenToCtx ¶
SetJwtTokenToCtx set the token (excluding prefix Bearer) to the context in grpc client side Example:
authorization := "Bearer jwt-token"
ctx := SetJwtTokenToCtx(ctx, authorization) cli.GetByID(ctx, req)
func StreamClientCircuitBreaker ¶
func StreamClientCircuitBreaker(opts ...CircuitBreakerOption) grpc.StreamClientInterceptor
StreamClientCircuitBreaker client-side stream circuit breaker interceptor
func StreamClientLog ¶
func StreamClientLog(opts ...LogOption) grpc.StreamClientInterceptor
StreamClientLog client log stream interceptor
func StreamClientMetrics ¶
func StreamClientMetrics() grpc.StreamClientInterceptor
StreamClientMetrics client-side metrics stream interceptor
func StreamClientRecovery ¶
func StreamClientRecovery() grpc.StreamClientInterceptor
StreamClientRecovery client-side recovery stream interceptor
func StreamClientRequestID ¶
func StreamClientRequestID() grpc.StreamClientInterceptor
StreamClientRequestID gRPC 客户端流式请求 request_id 拦截器 功能: 1. 检查 outgoing metadata 中是否存在 request_id 2. 如果不存在,生成一个新的 request_id 并添加到 outgoing metadata 3. 确保客户端发出的每个流式请求都携带 request_id
使用场景: - gRPC 客户端发起流式调用时自动注入 request_id - 与 StreamServerRequestID 配合使用,实现流式请求的追踪
返回:
- grpc.StreamClientInterceptor: 流式客户端拦截器
func StreamClientRetry ¶
func StreamClientRetry(opts ...RetryOption) grpc.StreamClientInterceptor
StreamClientRetry client-side retry stream interceptor
func StreamClientTimeout ¶
func StreamClientTimeout(d time.Duration) grpc.StreamClientInterceptor
StreamClientTimeout server-side timeout interceptor
func StreamClientTracing ¶
func StreamClientTracing() grpc.StreamClientInterceptor
StreamClientTracing client-side tracing stream interceptor Deprecated: Use NewClientStatsHandler instead
func StreamServerCircuitBreaker ¶
func StreamServerCircuitBreaker(opts ...CircuitBreakerOption) grpc.StreamServerInterceptor
StreamServerCircuitBreaker server-side stream circuit breaker interceptor
func StreamServerJwtAuth ¶
func StreamServerJwtAuth(opts ...AuthOption) grpc.StreamServerInterceptor
StreamServerJwtAuth jwt stream interceptor
func StreamServerLog ¶
func StreamServerLog(opts ...LogOption) grpc.StreamServerInterceptor
StreamServerLog Server-side log stream interceptor
func StreamServerMetrics ¶
func StreamServerMetrics(opts ...metrics.Option) grpc.StreamServerInterceptor
StreamServerMetrics server-side metrics stream interceptor
func StreamServerRateLimit ¶
func StreamServerRateLimit(opts ...RatelimitOption) grpc.StreamServerInterceptor
StreamServerRateLimit server-side stream circuit breaker interceptor
func StreamServerRecovery ¶
func StreamServerRecovery() grpc.StreamServerInterceptor
StreamServerRecovery recovery stream interceptor
func StreamServerRequestID ¶
func StreamServerRequestID() grpc.StreamServerInterceptor
StreamServerRequestID gRPC 服务端流式请求 request_id 拦截器(待实现) TODO: 实现流式请求的 request_id 提取和注入逻辑
预期功能: 1. 从 stream context 的 incoming metadata 中提取 request_id 2. 如果不存在,生成一个新的 request_id 3. 确保流式请求也能正确追踪
返回:
- grpc.StreamServerInterceptor: 流式服务端拦截器
func StreamServerSimpleLog ¶
func StreamServerSimpleLog(opts ...LogOption) grpc.StreamServerInterceptor
StreamServerSimpleLog Server-side log stream interceptor, only print response
func StreamServerToken ¶
func StreamServerToken(f CheckToken) grpc.StreamServerInterceptor
StreamServerToken recovery stream token
func StreamServerTracing ¶
func StreamServerTracing() grpc.StreamServerInterceptor
StreamServerTracing server-side tracing stream interceptor Deprecated: Use NewServerStatsHandler instead
func UnaryClientCircuitBreaker ¶
func UnaryClientCircuitBreaker(opts ...CircuitBreakerOption) grpc.UnaryClientInterceptor
UnaryClientCircuitBreaker client-side unary circuit breaker interceptor
func UnaryClientLog ¶
func UnaryClientLog(opts ...LogOption) grpc.UnaryClientInterceptor
UnaryClientLog client log unary interceptor
func UnaryClientMetrics ¶
func UnaryClientMetrics() grpc.UnaryClientInterceptor
UnaryClientMetrics client-side metrics unary interceptor
func UnaryClientRecovery ¶
func UnaryClientRecovery() grpc.UnaryClientInterceptor
UnaryClientRecovery client-side unary recovery
func UnaryClientRequestID ¶
func UnaryClientRequestID() grpc.UnaryClientInterceptor
UnaryClientRequestID gRPC 客户端一元请求 request_id 拦截器 功能: 1. 检查 outgoing metadata 中是否存在 request_id 2. 如果不存在,生成一个新的 request_id 并添加到 outgoing metadata 3. 确保客户端发出的每个请求都携带 request_id,便于全链路追踪
使用场景: - gRPC 客户端发起一元调用时自动注入 request_id - 与 UnaryServerRequestID 配合使用,实现完整的请求追踪
返回:
- grpc.UnaryClientInterceptor: 一元客户端拦截器
func UnaryClientRetry ¶
func UnaryClientRetry(opts ...RetryOption) grpc.UnaryClientInterceptor
UnaryClientRetry client-side retry unary interceptor
func UnaryClientTimeout ¶
func UnaryClientTimeout(d time.Duration) grpc.UnaryClientInterceptor
UnaryClientTimeout client-side timeout unary interceptor
func UnaryClientTracing ¶
func UnaryClientTracing() grpc.UnaryClientInterceptor
UnaryClientTracing client-side tracing unary interceptor Deprecated: Use NewClientStatsHandler instead
func UnaryServerCircuitBreaker ¶
func UnaryServerCircuitBreaker(opts ...CircuitBreakerOption) grpc.UnaryServerInterceptor
UnaryServerCircuitBreaker server-side unary circuit breaker interceptor
func UnaryServerJwtAuth ¶
func UnaryServerJwtAuth(opts ...AuthOption) grpc.UnaryServerInterceptor
UnaryServerJwtAuth jwt unary interceptor
func UnaryServerLog ¶
func UnaryServerLog(opts ...LogOption) grpc.UnaryServerInterceptor
UnaryServerLog server-side log unary interceptor
func UnaryServerMetrics ¶
func UnaryServerMetrics(opts ...metrics.Option) grpc.UnaryServerInterceptor
UnaryServerMetrics server-side metrics unary interceptor
func UnaryServerRateLimit ¶
func UnaryServerRateLimit(opts ...RatelimitOption) grpc.UnaryServerInterceptor
UnaryServerRateLimit server-side unary circuit breaker interceptor
func UnaryServerRecovery ¶
func UnaryServerRecovery() grpc.UnaryServerInterceptor
UnaryServerRecovery recovery unary interceptor
func UnaryServerRequestID ¶
func UnaryServerRequestID() grpc.UnaryServerInterceptor
UnaryServerRequestID gRPC 服务端一元请求 request_id 拦截器 功能: 1. 从 incoming metadata 中提取 request_id 2. 如果不存在,生成一个新的 request_id 并添加到 incoming metadata 3. 确保服务端处理的每个请求都有 request_id,便于日志记录和链路追踪
使用场景: - gRPC 服务端接收一元请求时自动提取或生成 request_id - 与 UnaryClientRequestID 配合使用,实现完整的请求追踪 - 日志系统可以通过 ServerCtxRequestIDField 自动记录 request_id
返回:
- grpc.UnaryServerInterceptor: 一元服务端拦截器
func UnaryServerSimpleLog ¶
func UnaryServerSimpleLog(opts ...LogOption) grpc.UnaryServerInterceptor
UnaryServerSimpleLog server-side log unary interceptor, only print response
func UnaryServerToken ¶
func UnaryServerToken(f CheckToken) grpc.UnaryServerInterceptor
UnaryServerToken recovery unary token
func UnaryServerTracing ¶
func UnaryServerTracing() grpc.UnaryServerInterceptor
UnaryServerTracing server-side tracing unary interceptor Deprecated: Use NewServerStatsHandler instead
func VerifySignatureInterceptor ¶ added in v1.1.39
func VerifySignatureInterceptor(opts ...SignOption) grpc.UnaryServerInterceptor
VerifySignatureInterceptor 是一个 unary 拦截器,用于验证签名
func WrapServerCtx ¶
WrapServerCtx 包装 gRPC 服务端上下文,主要用于: 1. 从 gRPC incoming metadata 中提取 request_id,并设置到 context 中 2. 支持通过可变参数 kvs 添加额外的自定义键值对到 context 3. 确保后续的日志记录、链路追踪等功能能够正确获取 request_id
使用场景: - gRPC Server 端拦截器中,标准化上下文信息 - HTTP 到 gRPC 的桥接场景中,传递请求元数据 - 需要在多个服务调用之间保持上下文一致性的场景
注意:
- 该函数会从 incoming metadata 中提取 request_id,如果不存在则为空字符串
- 如果在非 gRPC 场景(如 RabbitMQ、Kafka 消费者)中使用,incoming metadata 为空 会导致提取的 request_id 为空,可能覆盖之前设置的值
- 在非 gRPC 场景中,建议直接使用 context.WithValue 设置 request_id
Types ¶
type AuthOption ¶
type AuthOption func(*authOptions)
AuthOption setting the Authentication Field
func WithAuthClaimsName ¶
func WithAuthClaimsName(claimsName string) AuthOption
WithAuthClaimsName set the key name of the information in ctx for authentication
func WithAuthIgnoreMethods ¶
func WithAuthIgnoreMethods(fullMethodNames ...string) AuthOption
WithAuthIgnoreMethods ways to ignore forensics fullMethodName format: /packageName.serviceName/methodName, example /api.userExample.v1.userExampleService/GetByID
func WithAuthScheme ¶
func WithAuthScheme(scheme string) AuthOption
WithAuthScheme set the message prefix for authentication
func WithCustomVerify ¶ added in v1.0.49
func WithCustomVerify(verify CustomVerifyFn) AuthOption
WithCustomVerify set the custom verify function for authentication
func WithStandardVerify ¶ added in v1.0.49
func WithStandardVerify(verify StandardVerifyFn) AuthOption
WithStandardVerify set the standard verify function for authentication
type CheckToken ¶
CheckToken check app id and app key Example:
var f CheckToken=func(appID string, appKey string) error{
if appID != targetAppID || appKey != targetAppKey {
return status.Errorf(codes.Unauthenticated, "app id or app key checksum failure")
}
return nil
}
type CircuitBreakerOption ¶
type CircuitBreakerOption func(*circuitBreakerOptions)
CircuitBreakerOption set the circuit breaker circuitBreakerOptions.
func WithGroup ¶
func WithGroup(g *group.Group) CircuitBreakerOption
WithGroup with circuit breaker group. NOTE: implements generics circuitbreaker.CircuitBreaker
func WithUnaryServerDegradeHandler ¶
func WithUnaryServerDegradeHandler(handler func(ctx context.Context, req interface{}) (reply interface{}, err error)) CircuitBreakerOption
WithUnaryServerDegradeHandler unary server degrade handler function
func WithValidCode ¶
func WithValidCode(code ...codes.Code) CircuitBreakerOption
WithValidCode rpc code to mark failed
type CustomVerifyFn ¶ added in v1.0.49
CustomVerifyFn verify custom function, tokenTail32 is the last 32 characters of the token.
type KV ¶
type KV struct {
Key string // 上下文的键
Val interface{} // 上下文的值
}
KV 键值对结构体,用于在 WrapServerCtx 中传递自定义的上下文数据
type LogOption ¶
type LogOption func(*logOptions)
LogOption log settings
func WithLogFields ¶
WithLogFields adding a custom print field
func WithLogFrom ¶ added in v1.0.3
WithLogFrom logger logFrom
func WithLogIgnoreMethods ¶
WithLogIgnoreMethods ignore printing methods fullMethodName format: /packageName.serviceName/methodName, example /api.userExample.v1.userExampleService/GetByID
func WithReplaceGRPCLogger ¶
func WithReplaceGRPCLogger() LogOption
WithReplaceGRPCLogger replace grpc logger v2
type RatelimitOption ¶
type RatelimitOption func(*ratelimitOptions)
RatelimitOption set the rate limits ratelimitOptions.
func WithCPUQuota ¶
func WithCPUQuota(quota float64) RatelimitOption
WithCPUQuota with real cpu quota(if it can not collect from process correct);
func WithCPUThreshold ¶
func WithCPUThreshold(threshold int64) RatelimitOption
WithCPUThreshold with cpu threshold
type RetryOption ¶
type RetryOption func(*retryOptions)
RetryOption set the retry retryOptions.
func WithRetryErrCodes ¶
func WithRetryErrCodes(errCodes ...codes.Code) RetryOption
WithRetryErrCodes set the trigger retry error code
func WithRetryInterval ¶
func WithRetryInterval(t time.Duration) RetryOption
WithRetryInterval set the retry interval from 1 ms to 10 seconds
func WithRetryTimes ¶
func WithRetryTimes(n uint) RetryOption
WithRetryTimes set number of retries, max 10
type SignOption ¶ added in v1.1.39
type SignOption func(*signOption)
SignOption 设置签名字段
func WithSignExpiredTime ¶ added in v1.1.56
func WithSignExpiredTime(signExpiredTime time.Duration) SignOption
WithSignExpiredTime 设置签名过期时间
func WithSignIgnoreMethods ¶ added in v1.1.39
func WithSignIgnoreMethods(fullMethodNames ...string) SignOption
WithSignIgnoreMethods 设置忽略签名验证的方法 fullMethodName 格式: /packageName.serviceName/methodName, 示例 /api.userExample.v1.userExampleService/GetByID