首页 > 文章列表 > 使用Protobuf导入已知类型(例如时间戳)从google.golang.org/protobuf中获取

使用Protobuf导入已知类型(例如时间戳)从google.golang.org/protobuf中获取

460 2024-03-28
问题内容

到目前为止,我使用的是 github.com/golang/protobuf。今天我收到了警告 module github.com/golang/protobuf is deprecated: use the "google.golang.org/protobuf" modulerather. 所以我这样做了,并且过渡顺利。但我的项目仍然依赖于 github.com/golang/protobuf,我想摆脱的存储库。原因是我在 .proto 文件中使用已知类型:

import "google/protobuf/timestamp.proto";
import "google/protobuf/wrappers.proto";

当我运行 protoc (v3.12.4) 生成相应的 go 文件时,这将被解析为

import (
    timestamp "github.com/golang/protobuf/ptypes/timestamp"
    wrappers "github.com/golang/protobuf/ptypes/wrappers"
)

,导致已弃用的依赖项仍在使用中。 不确定这是否重要,但我依赖这些 protoc 插件:

$ go install google.golang.org/protobuf/cmd/[email protected]
$ go install google.golang.org/grpc/cmd/[email protected]

,据我所知这是最新的。

在寻找最新的 timestamp 类型时,我偶然发现了 https://pkg.go.dev/google.golang.org/protobuf/types/known/timestamppb。该网址表明它可能属于所需的 google.golang.org/protobuf 包,但我不知道如何正确导入它。底层 github 存储库包含一个自述文件,它告诉我:

types/known/timestamppb: Package timestamppb is the generated package for google/protobuf/timestamp.proto.

但是 google/protobuf/timestamp.proto 是我当前在 .proto 文件中使用的导入,并且我仍然以 import timestamp "github.com/golang/protobuf/ptypes/timestamp" 结束,这是已弃用的依赖项。

我对如何解决所有这些依赖关系有点迷失,而且我不知道在哪里可以找到缺少的部分来摆脱 github.com/golang/protobuf 依赖关系。有吗?


正确答案


这很令人困惑,因为 Google 对 Go 进行了 v1 (github.com/golang/protobuf) 到 v2 (google.golang.org/protobuf) 的更改。

v2 的README 提供了很好的概要和也有一篇关于此的博客文章(我无法再找到),但请参阅 A New Go API for Protocol缓冲区

此更改(对 v2)还包括用于 Google 众所周知的类型请参阅包索引.

此更改的结果是您应该更新 protoc-gen-goprotoc-gen-go-grpc 然后,更新 protoc (v3.12.4)已旧(2020 年 7 月)。新插件将生成正确引用 Google 提供的新 GWT Go 存根的 Go 存根。

发生 API 切换的 protoc-gen-go 版本是 1。 4.0,参见“概述”。

原始 import 引用(例如 google/protobuf/timestamp.proto更改。