登录
首页 >  Golang >  Go教程

GolanggRPC拦截器实现教程

时间:2025-10-21 09:18:31 446浏览 收藏

珍惜时间,勤奋学习!今天给大家带来《Golang实现gRPC拦截器教程》,正文内容主要涉及到等等,如果你正在学习Golang,或者是对Golang有疑问,欢迎大家关注我!后面我会持续更新相关内容的,希望都能帮到正在学习的大家!

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

如何在Golang中实现gRPC拦截器

在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服务器时注册该拦截器:

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和服务端/客户端分别设置。

服务端流拦截器示例:

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中实现横切关注点的核心机制,合理使用能让代码更清晰、可维护性更高。

好了,本文到此结束,带大家了解了《GolanggRPC拦截器实现教程》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

相关阅读
更多>
最新阅读
更多>
课程推荐
更多>