Home > OS >  protobuf with Go not able to compile to the desired folder with paths=source_relative
protobuf with Go not able to compile to the desired folder with paths=source_relative

Time:07-02

I want to generate .pb.go files to the ./pb folder. I have my .proto files under ./proto folder. I ran this command in my root folder:

protoc --go_out=./pb/ --go_opt=paths=source_relative ./proto/*.proto

However, my .go files always end up under ./pb/proto instead of ./pb folder, like this:

.
|____pb
| |____proto
| | |____my_message_one.pb.go
| | |____my_message_two.pb.go
| | |____my_message_three.pb.go

The name of my module in go.mod is module grpc_tutorial and here's an example my .proto file:

syntax = "proto3";

option go_package="./grpc_tutorial/pb"; 

message Screen {
  string some_message = 1;
  string some_message_two = 2;
  bool some_bool = 3;
}

Is there anything wrong with my command or proto file?

CodePudding user response:

Just remove --go_opt=paths=source_relative.

If you want the generated files end up in ./pb, then the option --go_out=./pb/ already specifies the correct output.

By adding source_relative, the output mirrors the disposition of the files in the source folder (documentation):

If the paths=source_relative flag is specified, the output file is placed in the same relative directory as the input file. For example, an input file protos/buzz.proto results in an output file at protos/buzz.pb.go.

Since your source files are located inside the ./proto folder, with source_relative the output files also end up inside a ./proto folder.

That entire output in turn ends up right where the --go_out flag specified, i.e. under ./pb. This is why finally the path of a generated file looks like ./pb/proto/my_message_one.pb.go, as you showed.

By removing the source_relative option, the output instead is not relativized to the source folder and goes directly into ./pb.

The command you want in this case is just:

protoc --go_out=./pb/ ./proto/*.proto
  • Related