Dotan
Dotan

Reputation: 7622

protobuf golang import .proto and .pb.proto from different directories

I have a library called myProtos which looks like this

.
|-- proto
|---- hello.proto
|
|-- generated
└---- hello.pb.go

I have a .proto file outside called example.proto that should import hello.proto

So the top of the file looks like this:

syntax = "proto3";
package example;
import "path/to/myProtos/proto/hello.proto"

Now, when I compile example.proto I get an import error on example.pb.go because it has the import line import "path/to/myProtos/proto/hello.pb.go"

I tried adding both import paths, but I get an 'import but not used error'. I also tried doing relative imports and passing both directories as flags to protoc, which worked, but I need the import path in the go file to be absolute.

How can I tell protoc that on the go file the path is different?

Is there a better 'best practice' in this case?

Upvotes: 5

Views: 11098

Answers (2)

Jendrik
Jendrik

Reputation: 186

What worked for me is to define option go_package = "github.com/<your-account>/<your-cool-project>/<sub-dirs>

Let's assume you have the folder structure your stated:

.
|-- proto
|---- hello.proto
|
|-- generated
└---- hello.pb.go

In your case you would add option go_package = "<path>/<in>/<GOPATH>/generated" to hello.proto. What is important is that you then have to run

protoc -I. --go_out=$GOPATH ./*.proto

Generally, I would generate the go files alongside the proto files to keep the import paths the same for proto and go files. But this might be a matter of taste. In that case you would then simply set option go_package = "<path>/<in>/<GOPATH>/proto" to hello.proto.

In both cases a relative import of the .proto file should now resolve to the proper import in the generated Go code and the .pb.go files should also be put into the proper Go package folders.

Upvotes: 2

Mustansir Zia
Mustansir Zia

Reputation: 1004

Use package generated; inside your hello.proto file.

Then, protoc -I proto/ proto/*.proto --go_out=generated will generate a hello.pb.go inside generated folder by the package name of generated.

The package inside the proto files tells the protobuf generator which package to use inside the generated file.

Upvotes: -1

Related Questions