如何在 gRPC 原型文件中创建关联?

How do I create associations in gRPC proto files?

我可能会以错误的方式处理它,但我想定义两个或多个结构(消息)之间的关系。

以 Whosebug 为例,假设我有一个 LabelService 用于标签上的 CRUD 操作。我还有一个 QuestionService,其中 Question 可以有 Labels。我们还假设我有一个 UserService 和一个 User 也可以附加标签

# label.proto
service LabelService {
    rpc CreateLabel() returns();
    ...etc
}
message Label {
   string text = 1;
}

但现在我想创建我的 QuestionServiceQuestion 消息。我是否以某种方式关联这两个文件,或者这种级别的关联是在 go 代码中完成的?

# question.proto
service QuestionService {
    rpc CreateQuestion() returns();
    ...etc
}
message Question {
   string text = 1;
   repeat Label labels = 2 # <-- how to do this?
}

# user.proto
service UserService {
    rpc CreateQuestion() returns();
    ...etc
}
message User {
   string name = 1;
   repeat Label labels = 2 # <-- how to do this?
}

我想我很困惑,因为对于 REST API 和使用 gorm.io 例如,我会在结构中设置关联并让 gorm.io 创建表。

您是否已经在 question.proto 中导入了 user.proto?

在question.proto

import "user.proto" <- 我想你可以使用 Label labels

来自docs

import "myproject/other_protos.proto";

所以只需将 question.proto 中的 import 添加到 user.proto。这与导入其他标准 proto 定义(如 timestampduration:

时没有什么不同
import "google/protobuf/timestamp.proto";
import "google/protobuf/duration.proto";