Add tags/prefix to gRPC method to distinguish private and public methods

Viewed 58

I would like to have some kind of tags / prefix on gRPC methods to distinguish private and public methods, so I can easily setup interceptor which will have condition based on that.

Example:

message ItemData {
  int32 id = 1;
  string title = 2;
  string description = 3;
  float price = 4;
  string currency = 5;
  int32 owner_id = 6;
  int32 category_id = 7;
}

message GetItemsRequest {
  int32 category_id = 1;
  string title = 2;
}

message GetItemsResponse {
  repeated ItemData items = 1;
}

service ItemsService{
  rpc GetItems(GetItemsRequest) returns (GetItemsResponse){
    option (google.api.http) = {
      get: "/v1/get-items"
    };
  }
  rpc GetMyItems(GetItemsRequest) returns (GetItemsRequest){}
}

So instead of using that kind of naming, I would like to add 'tag' to method and in interceptor something like this:

if info.Tag != "public" {
        if err := authorize(ctx); err != nil {
            return nil, err
        }
    }

I have found a way to add custom option tags to methods, but can't find how to read it in interceptor

extend google.protobuf.MethodOptions {
  optional bool private = 50006;
}

service ItemsService{
  rpc CreateItem(CreateItemRequest) returns (CreateItemResponse){
    option (private) = true;
  }
}
1 Answers

If we have a proto like as :

syntax = "proto3";

import "google/protobuf/descriptor.proto";

extend google.protobuf.MessageOptions {
  string foo = 50001;
}


message MyMessage {
  option (foo) = "bar";
}

so, we can get the option's value with this code:

m := mypackage.MyMessage{}
_, md := descriptor.MessageDescriptorProto(&m)
ex := proto.GetExtension(md.Options, mypackage.E_Foo)
if s, ok := ex.(string); ok {
    fmt.Printf("MyMessage.GetExtension: %s\n", s)
}

Thanks to this thread: Implement custom options

Related