前言

上篇文章《Go - 如何编写 ProtoBuf 插件 (二) 》,分享了基于 自定义选项 定义了 interceptor 插件,而后在 helloworld.proto 中应用了插件,最初在 golang 代码中获取到应用的插件信息。

接上篇,持续分享。

既然获取到了插件信息,咱们就能够应用它们。本文次要分享在 grpc.ServerOption 中的 grpc.UnaryInterceptor 中应用。

演示代码

还是以上篇文章中 helloworld.proto 为例。

// 生成 helloworld.pb.go// 生成 helloworld_grpc.pb.go// 应用的 protoc --version 为 libprotoc 3.18.1// 应用的 protoc-gen-go --version 为 protoc-gen-go v1.27.1// 应用的 protoc-gen-go-grpc --version 为 protoc-gen-go-grpc 1.1.0// 在根目录下执行 protoc 命令protoc --go_out=helloworld/gen --go-grpc_out=helloworld/gen helloworld/helloworld.proto

一、基于上篇文章中获取 options 的代码进行批改,次要是将其存入到构造体即可。

// 演示代码,构造体var handlers = &struct {    Methods  map[string]*options.MethodHandler  // FullMethod : Handler    Services map[string]*options.ServiceHandler // FullMethod : Handler}{    Methods:  make(map[string]*options.MethodHandler),    Services: make(map[string]*options.ServiceHandler),}

二、在 grpc.NewServer 中应用拦截器。

// 演示代码serverOptions := []grpc.ServerOption{    grpc.UnaryInterceptor(unaryServerInterceptor()),}srv := grpc.NewServer(serverOptions...)resolveFileDescriptor() // 解析 options 扩大项

三、在 unaryServerInterceptor() 办法中,能够依据以后申请的服务名和办法名获取到对应设置的 options

// 演示代码fullMethod := strings.Split(info.FullMethod, "/")serviceName := fullMethod[1]// 获取 service optionsgetServiceHandler(serviceName)// 获取 method optionsgetMethodHandler(info.FullMethod)

四、本人写一个 grpcclient 调用一下即可。

--- /helloworld.Greeter/SayHello1 ---service use interceptor authorization: login_tokenmethod use interceptor whitelist: ip_whitelistmethod use interceptor logger: true

至此,在 grpc.UnaryInterceptor 中就能够获取到 options 了,其余演示代码我就不贴了。

最初,通过获取到的 options,便能够执行本人定义的具体方法。

小结

通过最近的 “如何编写 ProtoBuf 插件” 这三篇文章,置信你对编写 ProtoBuf 插件有一点小的意识,心愿对你可能有所帮忙。

举荐浏览

  • Go - 如何编写 ProtoBuf 插件 (二) ?
  • Go - 如何编写 ProtoBuf 插件 (一) ?
  • Go - 对于 protoc 工具的小纳闷
  • Go - 对于 .proto 文件的小思考
  • Go - 基于逃逸剖析来晋升程序性能