简体   繁体   中英

Error importing and using other .proto files when using protoc to generate golang code

I've been using protoc to generate golang gRPC client and server code without issues. Since I have multiple gRPC services that use the same data types, I'd like to refer to a base.proto for these types rather than copy and paste, which is extra work and may result in out of sync issues.

Here's a sample of base.proto:

syntax = "proto3";
package base;
message Empty {
}
message Label {
   string Key = 1;
   string Value = 2;
}

Here's a sample specific .proto:

syntax = "proto3";
import = "base.proto";
package publisher;
service ClientPublisher {
 rpc Publish(stream base.Label) returns (base.Empty) {}
}

And, here's my command:

protoc -I system-client-go/ system-client-go/client/publisher.proto --go_out=plugins=grpc:system-client-go --proto_path=system-client-go/

No matter what I try, it throws this:

2019/08/01 15:31:31 protoc-gen-go: error:bad Go source code was generated: 273:7: expected type, found '.' (and 10 more errors) which corresponds to the line: rpc Publish(stream base.Label) returns (base.Empty) {}

Any ideas?

This kind of error normally is because your relative path is wrong. Try to put the specific proto file in a directory and import it like

import "exampleproject/specific.proto";

If both files are in the same directory the solution is explained in this thread => https://github.com/golang/protobuf/issues/322

Basically, golang only allows one package per directory. So protoc-gen-go is considering them like 2 separate libraries.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM