答案:Golang中通过grpc.UnaryServerInterceptor和grpc.StreamInterceptor实现服务端与客户端的拦截器,用于统一处理日志、认证等逻辑;支持一元和流式两种类型,可结合go-grpc-middleware库组合多个拦截器,提升代码可维护性。

在Golang中实现gRPC拦截器,主要是通过在服务端或客户端注册拦截函数,来统一处理请求前后的逻辑,比如日志、认证、错误处理等。gRPC Go库支持两种类型的拦截器:一元拦截器(Unary Interceptor)和流式拦截器(Streaming Interceptor)。
一、服务端一元拦截器
服务端一元拦截器用于处理普通的RPC调用(非流式)。你可以通过grpc.UnaryServerInterceptor选项注册一个拦截函数。
定义一个简单的日志拦截器:
func loggingUnaryInterceptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
fmt.Printf(“Received request: %s\n”, info.FullMethod)
resp, err := handler(ctx, req)
if err != nil {
fmt.Printf(“Error: %v\n”, err)
}
return resp, err
}
在启动gRPC服务器时注册该拦截器:
立即学习“go语言免费学习笔记(深入)”;
server := grpc.NewServer(
grpc.UnaryInterceptor(loggingUnaryInterceptor),
)
二、客户端一元拦截器
客户端拦截器可用于添加认证头、记录请求耗时等。使用grpc.WithUnaryInterceptor配置客户端。
示例:在每个请求中添加认证token:
func authUnaryInterceptor(ctx context.Context, method string, req, reply interface{},
cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts …grpc.CallOption) error {
ctx = metadata.AppendToOutgoingContext(ctx, “authorization”, “Bearer “)
return invoker(ctx, method, req, reply, cc, opts…)
}
创建客户端连接时启用拦截器:
conn, err := grpc.Dial(“localhost:50051”,
grpc.WithInsecure(),
grpc.WithUnaryInterceptor(authUnaryInterceptor),
)
三、流式拦截器
对于流式RPC(如 server streaming 或双向流),需要使用流式拦截器。gRPC不直接提供通用的流拦截器选项,但可以使用grpc.StreamInterceptor和服务端/客户端分别设置。
Replit Ghostwrite
一种基于 ML 的工具,可提供代码完成、生成、转换和编辑器内搜索功能。
93 查看详情
服务端流拦截器示例:
func loggingStreamInterceptor(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo,
handler grpc.StreamHandler) error {
fmt.Printf(“Streaming request: %s\n”, info.FullMethod)
return handler(srv, ss)
}
注册方式:
server := grpc.NewServer(
grpc.StreamInterceptor(loggingStreamInterceptor),
)
客户端流拦截器可通过grpc.WithStreamInterceptor设置,用法类似。
四、使用中间件组合多个拦截器
实际项目中通常需要多个拦截器(如日志、recover、认证)。可以使用开源库github.com/grpc-ecosystem/go-grpc-middleware简化组合。
安装:
go get github.com/grpc-ecosystem/go-grpc-middleware
组合多个一元拦截器:
import “github.com/grpc-ecosystem/go-grpc-middleware”
interceptors := grpc_middleware.ChainUnaryServer(
loggingUnaryInterceptor,
recoveryUnaryInterceptor,
)
server := grpc.NewServer(
grpc.UnaryInterceptor(interceptors),
)
基本上就这些。拦截器是gRPC中实现横切关注点的核心机制,合理使用能让代码更清晰、可维护性更高。
以上就是如何在Golang中实现gRPC拦截器的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1089687.html
微信扫一扫
支付宝扫一扫