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

问题描述

我可能用错了方法,但我想定义两个或多个结构(消息)之间的关系。

以 StackOverflow 为例,假设我有一个 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 创建表。

解决方法

来自docs

import "myproject/other_protos.proto";

所以只需在您的 import 中添加一个 question.proto 到您的 user.proto。这与导入其他标准 proto 定义(如 timestampduration)没有什么不同:

import "google/protobuf/timestamp.proto";
import "google/protobuf/duration.proto";
,

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

in question.proto

import "user.proto" Label labels