问题描述
我是 Protocol Buffers 和 gRPC 的新手。现在我正在尝试使用 Go 中的 grpc + grpc-gateway 构建客户端/服务器架构。
我尝试遵循一些示例,但最终总是遇到相同的问题。
使用 protoc
生成代码后,我运行 go build
并收到此错误:
proto/helloworld/hello_world.pb.gw.go:64:2: cannot use msg (type *HelloReply) as type protoreflect.ProtoMessage in return argument:
*HelloReply does not implement protoreflect.ProtoMessage (missing ProtoReflect method)
proto/helloworld/hello_world.pb.gw.go:98:2: cannot use msg (type *HelloReply) as type protoreflect.ProtoMessage in return argument:
*HelloReply does not implement protoreflect.ProtoMessage (missing ProtoReflect method)
这是go.mod
:
module github.com/riccardopedrielli/grpc-gateway-test
go 1.15
require (
github.com/golang/protobuf v1.4.3
github.com/grpc-ecosystem/grpc-gateway/v2 v2.2.0
google.golang.org/genproto v0.0.0-20210207032614-bba0dbe2a9ea
google.golang.org/grpc v1.35.0
google.golang.org/protobuf v1.25.0
)
这是hello_world.proto
:
Syntax = "proto3";
package helloworld;
import "google/api/annotations.proto";
option go_package = "github.com/riccardopedrielli/grpc-gateway-test/proto/helloworld";
// Here is the overall greeting service deFinition where we define all our endpoints
service Greeter {
// Sends a greeting
rpc SayHello (HelloRequest) returns (HelloReply) {
option (google.api.http) = {
get: "/v1/example/echo/{name}"
};
}
}
// The request message containing the user's name
message HelloRequest {
string name = 1;
}
// The response message containing the greetings
message HelloReply {
string message = 1;
}
这是存储库的链接:https://github.com/riccardopedrielli/grpc-gateway-test
我看到生成的 go 文件之间的区别在于它们导入了不同的 protobuf 库。protoc-gen-go
生成的导入 github.com/golang/protobuf/proto
.protoc-gen-grpc-gateway
生成的导入 google.golang.org/protobuf/proto
.
这可能是问题的原因吗?
我仍然不清楚应该使用哪一个以及如何在两个生成器中强制使用相同的方法。
我是 grpc 的新手,在这一点上很迷茫,所以我可以省略一些重要的信息。欢迎提出任何建议。
谢谢
解决方法
好的,我解决了这个问题。
我通过 snap 安装了 protoc
并且稳定频道的版本为 3.11.4
现在我升级到 3.14.0
并且一切正常。
为了生成存根,我们可以使用 protoc
或 buf
。 protoc
是业界广泛使用的更经典的生成体验。尽管如此,它的学习曲线非常陡峭。 buf
是一种较新的工具,其构建时考虑到了用户体验和速度。它还提供 linting 和破坏性更改检测,而 protoc
没有提供。
您应该查看关于 gRPC-Gateway 的教程系列,即 https://grpc-ecosystem.github.io/grpc-gateway/docs/tutorials/。另外,您可以参考我的简单 hello world 程序,该程序使用 gRPC-Gateway,即 https://github.com/iamrajiv/helloworld-grpc-gateway。