Preface

We need to know that the proto3 and proto2 are not completely compatible.

For details, please refer to the official documents:

If the above link cannot be opened, you can visit this document: Overview-语雀 .

Custom options

In proto3 , the common way to implement plug-ins is to use the custom option, which is the extend tag. The supported extend Options are:

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

For specific writing, please refer to:

import "google/protobuf/descriptor.proto";

extend google.protobuf.MessageOptions {
  optional string my_option = 51234;
}

message MyMessage {
  option (my_option) = "Hello world!";
}

Demand scenario

Suppose, our demand scenario is like this:

We have many interceptors. Different service may use one or more interceptors, and different method may also use one or more interceptors. In helloworld.proto

  • service Greeter{} supports login token verification
  • rpc SayHello1() supports IP whitelist restriction and logging
  • rpc SayHello2() supports the prohibition of logging
// helloworld.proto

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

message HelloRequest {
  string name = 1;
}

message HelloReply {
  string message = 1;
}

We need to define which interceptors are used by service proto Define which interceptors are used by method In this way, the proto file will be more semantic and clearer. When you see the defined file, you can see the interceptor used at a glance.

How to realize this function?

At this time, we need to use the MethodOptions and ServiceOptions options. From the name, you can probably guess that MethodOptions is the definition method option, and ServiceOptions is the definition service option.

extend google.protobuf.MethodOptions {
  ...
}

extend google.protobuf.ServiceOptions {
  ...
}

Do you have any ideas for realization? Welcome to leave a comment~

Recommended reading


程序员新亮
2.9k 声望1.2k 粉丝

GitHub 9K+ Star,其中适合 Go 新手的开箱即用项目 go-gin-api 5.2K Star:[链接],联系我:wx-xinliang