如何在.proto文件中正确导入go模型

我目前正在使用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)如果是,那么正确的语法是什么?

对此我是陌生的,因此,如果问题看起来很愚蠢,请大笑并忘记吧。

qq568957159 回答:如何在.proto文件中正确导入go模型

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

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

本文链接:https://www.f2er.com/3104549.html

大家都在问