preface

The previous article, “Go – How to Write a ProtoBuf plugin (II)”, shared that the interceptor plugin is defined based on custom options, then used in helloworld.proto, and finally got information about the plugin used in Golang code.

Continue to share.

Now that we have the plug-in information, we can use it. This article is mainly shared with grpc.UnaryInterceptor in grpc.ServerOption.

Demo code

Again, use the helloWorld.proto example from the previous article.

// Generate helloWorld.pb. go // generate helloWorld_grpc.pb. go // use protoc --version is libProtoc 3.18.1 // use protoc-gen-go --version: protoc-gen-go v1.27.1 // Protoc-gen-go-grpc used --version: protoc-gen-go-grpc 1.1.0 // Run the protoc command in the root directory protoc --go_out=helloworld/gen --go-grpc_out=helloworld/gen helloworld/helloworld.protoCopy the code

1, based on the previous article to obtain the options of the code to modify, mainly in the structure can be saved.

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), }Copy the code

Use interceptors in grpc.newServer.

ServerOptions := [] grpc.serverOption {grpc.unaryInterceptor (unaryServerInterceptor()), } srv := grpc.NewServer(serverOptions...) ResolveFileDescriptor () // Parse options extensionsCopy the code

In the unaryServerInterceptor() method, you can get the corresponding options based on the requested service name and method name.

// fullMethod := strings.split (info.fullmethod, "/") serviceName := fullMethod[1] // getServiceHandler(serviceName) // Get method options getMethodHandler(info.FullMethod)Copy the code

Four, write a grpCClient call yourself.

--- /helloworld.Greeter/SayHello1 ---
service use interceptor authorization: login_token
method use interceptor whitelist: ip_whitelist
method use interceptor logger: true
Copy the code

At this point, the options are available in the grpc.UnaryInterceptor. I won’t post the other demo code.

Finally, with the options obtained, you can execute your own specific methods.

summary

With the recent three articles “How to write a ProtoBuf plugin”, I believe you have a little understanding of how to write a ProtoBuf plugin. I hope it will help you.

Recommended reading

  • Go – How to write a ProtoBuf plugin (ii)?
  • Go – How to write a ProtoBuf plugin (I)?
  • Go – a little confusion about the Protoc tool
  • Go – A little thought about.proto files
  • Go – Improves application performance based on escape analysis