middleware

package
v0.7.9 Latest Latest
Warning

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

Go to latest
Published: Feb 11, 2026 License: MIT Imports: 10 Imported by: 0

README

Middleware

middleware 包提供了 gRPC 服务的通用中间件(Interceptor)。

功能列表

1. Access Logger (GrpcAccessLogger)

提供详细的 gRPC 访问日志记录功能。

特性

  • 自动记录请求/响应耗时。
  • 自动提取 gRPC metadata 中的客户端信息(IP、System、Client、Version 等)。
  • 自动关联 TraceId(若缺失则自动生成)。
  • 记录 Request/Response JSON 载荷。

用法

import (
	"fmt"

	"github.com/fireflycore/go-micro/middleware"
	"google.golang.org/grpc"
)

// 创建 gRPC Server 时注入
s := grpc.NewServer(
	grpc.UnaryInterceptor(middleware.GrpcAccessLogger(func(b []byte, msg string) {
		// 自定义日志输出逻辑,例如写入文件或 stdout
		fmt.Println(string(b))
	})),
)
2. Metadata Propagation (PropagateIncomingMetadata)

将入站请求的 gRPC metadata 自动透传到出站 context 中。

场景

  • 在微服务调用链中,保持 TraceIdUserId 等上下文信息的连续传递。

用法

import (
	"github.com/fireflycore/go-micro/middleware"
	"google.golang.org/grpc"
)

s := grpc.NewServer(
	grpc.UnaryInterceptor(middleware.PropagateIncomingMetadata),
)

Documentation

Overview

Package middleware 提供 gRPC 中间件能力。

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GrpcAccessLogger

func GrpcAccessLogger(handle func(b []byte, msg string)) grpc.UnaryServerInterceptor

GrpcAccessLogger 返回一个 gRPC Unary 拦截器,用于输出访问日志。 handle 接收两类日志:b 为结构化 JSON,msg 为人类可读文本行; 字段包含 path/request/response/duration/status/trace_id 等,便于统一采集。

func PropagateIncomingMetadata

func PropagateIncomingMetadata(ctx context.Context, req interface{}, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error)

PropagateIncomingMetadata 将入站元数据传播到出站上下文中

Types

This section is empty.

Jump to

Keyboard shortcuts

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