我尝试使用 google api 注释在 gRPC 上使用 REST。
不幸的是,我面临一个 protoc 问题,告诉我 annotations.proto 不存在或有错误。
我尝试了几次修复都是徒劳的。
我什至尝试重新安装一个完整的堆栈,以防我做错了什么。
我将尽可能详细地向您详细说明我从全新安装中设置的完整行和文件。
从一个全新的 go install VM 我输入这些 shell 行:$ mkdir sources/golang
$ echo 'export GOPATH=$HOME/sources/golang' >> $HOME/.zshrc
$ source ~/.zshrc
$ cd sources/golang
$ mkdir src
$ cd src
$ export PATH=$PATH:$GOPATH/bin
$ go get -u google.golang.org/grpc
$ go get -u github.com/golang/protobuf/protoc-gen-go
$ go get -u github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway
$ go get -u github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger
$ mkdir -p test/proto/test
$ cd test/proto/test
$ vim test.proto
在我的 test.proto 文件中,我写了非常基本的行:
syntax = "proto3";
package main;
import "google/api/annotations.proto";
service Tester {
rpc Test (Request) returns (Reply) {
option (google.api.http) = { get: "/v1/test" };
}
}
message Request {
string Message = 1;
}
message Reply {
string Message = 1;
}
然后
$ cd $GOPATH/src
$ vim main.go
在我的 main.go 中,也非常基本:
package main
import (
tc "test/proto/test"
"context"
"fmt"
"log"
"net"
grpc "google.golang.org/grpc"
codes "google.golang.org/grpc/codes"
)
func main() {
err := StartServer("tcp", "127.0.0.1:50051")
if err != nil {
fmt.Printf("Error!! %s", err)
}
}
type Server struct {
tc.UnimplementedTesterServer
}
func (s *Server) Test(ctx context.Context, in *tc.Request) (*tc.Reply, error) {
return &tc.Reply{Message: ""}, nil
}
func StartServer(protocol string, port string) error {
lis, err := net.Listen(protocol, port)
if err != nil {
fmt.Printf("failed to listen: %v", err)
}
s := grpc.NewServer()
tc.RegisterTesterServer(s, &Server{})
error := s.Serve(lis)
if error != nil {
fmt.Printf("failed to serve: %v", error)
return error
}
return nil
}
最后,我尝试编译我的原型(prototype)文件:
$ protoc --proto_path=.:$GOPATH/src --go_out=plugins=grpc:. proto/*/*.proto
我系统地有以下错误:
proto/test/test.proto:5:1: Import "github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis/google/api/annotations.proto" was not found or had errors.
当我看到文件通过
go get ...
获取时, 它们被放置在 $GOPATH/pkg/mod/下例如,googleapis 的 annotations.proto 文件位于: $GOPATH/pkg/mod/github.com/grpc-ecosystem/grpc-gateway@v1.12.1/third_party/googleapis/google/api/annotations.proto
也许这是原因?
最佳答案
混合你的 protobuf 命令和你的 go 命令使得这比它需要的更复杂。只需关注 protobuf 来处理错误。
您正在导入“google/api/annotations.proto”
你的 proto_path 是 --proto_path=.:$GOPATH/src
这意味着当您执行 protoc 时,您应该将文件位于 ./google/api/annotations.proto 或 $GOPATH/src/google/api/annotations.proto
关于go - 无法使用 google/apis/annotations,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59620019/