preface

It’s important to remember that proto3 and Proto2 syntax are not completely compatible.

For details, please refer to official documents:

  • Overview
  • Language Guide (proto2)
  • Language Guide (proto3)

If the above link does not open, you can visit this document: Overview – Language Sparrow.

Custom options

With Proto3, a common way to implement plug-ins is to use a custom option, the extend tag, which supports the extend Options:

  • MethodOptions
  • ServiceOptions
  • EnumOptions
  • EnumValueOptions
  • MessageOptions
  • FieldOptions
  • FileOptions
  • OneofOptions
  • ExtensionRangeOptions

Specific writing method can be referred to:

import "google/protobuf/descriptor.proto"; extend google.protobuf.MessageOptions { optional string my_option = 51234; } message MyMessage { option (my_option) = "Hello world!" ; }Copy the code

Demand scenarios

Suppose our requirements scenario looks like this:

We have many interceptors, different services may use one or more interceptors, different methods may use one or more interceptors, in helloWorld.proto

  • service Greeter{}Support login token authentication
  • rpc SayHello1()supportIPWhitelist restrictions and logging
  • rpc SayHello2()Logs are disabled
// helloworld.proto

service Greeter {
  rpc SayHello1 (HelloRequest) returns (HelloReply) {}
  rpc SayHello2 (HelloRequest) returns (HelloReply) {}
}

message HelloRequest {
  string name = 1;
}

message HelloReply {
  string message = 1;
}
Copy the code

In the proto file, we need to define which interceptors are used by the service. Define which interceptors method uses? This makes the proto file more semantic and unambiguous, so that when you see the defined file, you can see the interceptor used at a glance.

How is this implemented?

In this case, we need to use the MethodOptions and ServiceOptions options options. As you can probably guess from the name, MethodOptions defines MethodOptions and ServiceOptions defines ServiceOptions.

extend google.protobuf.MethodOptions {
  ...
}

extend google.protobuf.ServiceOptions {
  ...
}
Copy the code

Any ideas on how to do that? Welcome to leave a comment

Recommended reading

  • Go – a little confusion about the Protoc tool
  • Go – A little thought about.proto files
  • Go – Use sync.waitGroup for concurrent operations
  • Go – Use sync.Map to solve the problem of Map concurrency security
  • Go – Improves application performance based on escape analysis