1

我目前正在使用 protobuf 将我们基于 rest api 的 go 服务迁移到 gRPC。我正在使用互联网上的一些示例,我的 service.proto 文件就像

syntax = "proto3";
package v1;

import "google/protobuf/timestamp.proto";

// Taks we have to do
message ToDo {
    // Unique integer identifier of the todo task
    int64 id = 1;
    // Title of the task
    string title = 2;
    // Detail description of the todo task
    string description = 3;
    // Date and time to remind the todo task
    google.protobuf.Timestamp reminder = 4;
}

// Request data to create new todo task
message CreateRequest{
    // API versioning: it is my best practice to specify version explicitly
    string api = 1;

    // Task entity to add
    ToDo toDo = 2;
}

// Response that contains data for created todo task
message CreateResponse{
    // API versioning: it is my best practice to specify version explicitly
    string api = 1;

    // ID of created task
    int64 id = 2;
}

// Service to manage list of todo tasks
service ToDoService {
    // Create new todo task
    rpc Create(CreateRequest) returns (CreateResponse);
}

现在在给定的代码片段中,我们可以看到我们在同一个 .proto 文件中定义了所有请求和响应。

我想在不同的 go 文件中定义这些,以便可以在整个项目中使用它们,例如 - 我有一个名为 CreateRequest.go 的模型文件,我可以以某种方式将其导入到这个 .proto 文件中以及项目的其余部分我也可以使用该 CreateRequest 模型,这样我就不必两次定义相同的模型。

1)有可能做到这一点吗?

2)如果是,那么正确的语法是什么?

我是新手,所以如果这个问题看起来很愚蠢,那就笑一笑然后忘记。

4

1 回答 1

0

一个名为 CreateRequest.go 的模型文件,我可以通过某种方式将它导入到这个 .proto 文件中”——这不是办法。要使用 proto 文件,1) 创建您的 api.proto 文件,不要忘记在其中添加类似“package apiv1”的包。2) 使用 protogen-go 将您的 proto 编译为 api.pb.go 3) 在该文件中创建一个“apihandler.go”文件和“import apivi”。因此,您正在将原始生成的包“apivi”导入到“apihandler.go”文件中。

与其为请求和响应分别提供 .proto 文件,不如根据您的 api 版本或项目的任何合理组件将它们隔离开来。

于 2019-11-20T17:42:14.423 回答