解决protoc-gen-go:通过添加“M”参数无法确定Go导入路径问题

xpt*_*xpt 8 go protocol-buffers protoc grpc-go

与 protoc-gen-go 相同的症状:无法确定“simple.proto”的 Go 导入路径

\n
\n

对于具有以下内容的简单原型文件。

\n
syntax="proto3";\n\npackage main;\n\nmessage Person {\n      string name = 1;\n      int32 age = 2; \n}\n
Run Code Online (Sandbox Code Playgroud)\n

我正在尝试使用 protoc 为其生成 go 代码。我跑:

\n
protoc --go_out=. --go_opt=paths=source_relative --go-grpc_out=. --go-grpc_opt=paths=source_relative simple.proto\n
Run Code Online (Sandbox Code Playgroud)\n

我收到以下错误:

\n
protoc-gen-go: unable to determine Go import path for "simple.proto"\n\nPlease specify either:\n        \xe2\x80\xa2 a "go_package" option in the .proto source file, or\n        \xe2\x80\xa2 a "M" argument on the command line.\n
Run Code Online (Sandbox Code Playgroud)\n
\n

那里的所有答案都集中在第一个选项 - 添加a "go_package" option in the .proto source file,但我正在寻找第二个选项“命令行上的“M”参数”的答案。

\n

与/sf/answers/4377844201/下的评论相同

\n

我正在寻找通过protoc更改模块路径的方法,为属于不同模块的客户端和服务器生成 Go 代码,我尝试使用go_opt=module,但它不适用于source_relative.

\n

有什么方法可以通过在命令行上添加“a“M”参数”来使其工作,而不是go_package在 .proto 源文件中添加“”选项?

\n

具体来说,对于\n https://github.com/mmcc007/go/blob/master/examples/helloworld/helloworld/helloworld.proto的文件

\n

以下是我失败的尝试:

\n
$ protoc --go_out=. --go_opt=paths=source_relative --go-grpc_out=. --go-grpc_opt=paths=source_relative --proto_path=examples/helloworld/helloworld helloworld.proto\xc2\xa0\n\nprotoc-gen-go: unable to determine Go import path for "helloworld.proto"\n. . .\n--go_out: protoc-gen-go: Plugin failed with status code 1.\n\n\n$ protoc --go_out=. --go_opt=paths=source_relative --go-grpc_out=. --go-grpc_opt=paths=source_relative --proto_path=examples/helloworld/helloworld --go_opt=Mhelloworld.proto=github.com/mmcc007/go/blob/master/examples/helloworld/helloworld helloworld.proto\xc2\xa0\n\nprotoc-gen-go-grpc: unable to determine Go import path for "helloworld.proto"\n. . .\n--go_out: protoc-gen-go: Plugin failed with status code 1.\n\n
Run Code Online (Sandbox Code Playgroud)\n

Chr*_* G. 8

我发现这可以--proto_path使用“THE M FLAG”轻松参考:-)

protoc --proto_path=./proto \
  --go_out=./go \
  --go_opt=Mhelloworld.proto=example.com/project/protos/fizz \
  ./proto/helloworld.proto
Run Code Online (Sandbox Code Playgroud)

注意:helloworld.proto 之前的 M

  • 我发现非常令人失望的是,您的答案是我发现的唯一信息来源,它最终帮助我实现了选择生成的 go 代码去哪里的简单任务。这些文档是找不到的,并且网络上的评论并没有真正解决这个简单的任务。谢谢@克里斯·G。 (3认同)
  • fwiw.-我同意@pablete - 文档中的简介实际上并没有解释是否在 PROTO_FILE 或 GO_IMPORT_PATH 中使用相对路径或绝对路径 - 另外 - GO_IMPORT_PATH 似乎是命名空间和文件路径的奇怪组合。我始终无法让“-go_opt=M”命令行参数正常工作,只能将“option go_package = ...”转储到我的 .proto 文件中。我使用这些相同的原始文件来生成一种语言 - 但无法让它们适用于 golang。 (2认同)