【问题标题】:Referencing external protos like google/rpc/status.proto引用外部 protos,如 google/rpc/status.proto
【发布时间】:2020-03-27 00:52:41
【问题描述】:

我想知道如何正确引用外部 proto 文件。假设我有一个引用标准 protobuf 类型的 .proto 文件,例如 Timestamp:

syntax = "proto3";
package api;

import "google/protobuf/timestamp.proto";

message ServerTimeResponse {
  google.protobuf.Timestamp ts = 1;
}

简单。编译时时间戳自动可用。

现在我添加一个外部 输入,说google.rpc.Status

syntax = "proto3";
package api;

import "google/protobuf/timestamp.proto";
import "google/rpc/status.proto";

message ServerTimeResponse {
  google.protobuf.Timestamp ts = 1;
  google.rpc.Status status = 2;
}

当然我们必须通过-I/--proto_path告诉protoc如何找到这个文件。

我的问题是:实际引用此文件的最佳做法是什么,特别是让版本控制满意? protobufs 似乎没有 go mod 等效项。我已经看到它逐字复制到项目中(例如在grpc-gateway 中)或只是从本地文件系统中引用。

【问题讨论】:

    标签: protocol-buffers


    【解决方案1】:

    我想你在这里回答了你自己的问题。我都成功完成了:手动逐字复制必要的文件(来自https://github.com/googleapis/googleapis/tree/master/googlehttps://github.com/protocolbuffers/protobuf/tree/master/src/google/protobuf),并引用文件的本地副本。

    如果您想这样做并让版本控制满意,您可以将这两个存储库添加为 git submodules 到您的存储库中。只需确保使用-I 将正确的位置传递给protoc。例如:

    cd $PROJECT_DIR
    mkdir third_party && cd third_party
    git submodule add https://github.com/googleapis/googleapis/tree/master/google
    cd $PROJECT_DIR
    <git commit the change>
    protoc -I third_party/google <the rest of your protoc command>
    

    至于引用文件的本地副本,并在尝试构建之前确保它们存在,您可能会发现在 Makefile 中添加类似以下内容会有所帮助(这是在 Go 构建环境中):

    go get -u github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway
    go get -u github.com/golang/protobuf/protoc-gen-go
    grpc_gateway_path=$(go list -m -f '{{.Dir}}' github.com/grpc-ecosystem/grpc-gateway)
    googleapis_path="$grpc_gateway_path/third_party/googleapis"
    protoc -I $googleapis_path --go_out=. <list of input files>
    

    【讨论】:

    • 我按照你的建议走子模块路线,效果很好,谢谢。
    • 很高兴听到它成功了!伟大的思想都一样:)
    • 我也非常喜欢您的go list -m 建议。如果我从 go 模块和子模块中得到相同的东西,它看起来很干净。我会试一试。再次感谢。
    猜你喜欢
    • 1970-01-01
    • 2019-07-29
    • 1970-01-01
    • 1970-01-01
    • 2019-05-03
    • 2020-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多