Search code examples
goprotocol-buffers

Resolve Go package naming conflict when compiling protobuf definitions with different packages


I'm using protoc to create some DTOs. The definitions are in the following structure:

/protobuf
|-- common.proto
|-- /api
    |-- /service
        |-- csvdownload.proto

My csvdownload.proto looks like this:

syntax = "proto3";
package protobuf.api.service;

import "common.proto";

option go_package = ".;service"; // golang

message CsvExportRequest {
    Common.Currency exportCurrency = 2;
    Common.Decimal rounding = 3;
}

and the stub of common.proto looks like this:

syntax = "proto3";
package protobuf;

option go_package = ".;gopb"; // golang

I'm attempt to compile csvdownload.proto by running the following command from the /protobuf directory:

protoc --go_out=gopb --go_opt=paths=source_relative .\api\service\csvdownload.proto

However, I'm getting the following error:

protoc-gen-go: Go package "." has inconsistent names gopb (common.proto) and service (api/service/csvdownload.proto)

I assume this to mean that the code cannot be generated because common.proto and csvdownload.proto have declared different packages but I'm not sure that should make a difference and, from my understanding of how Protobuf works, it shouldn't hinder my ability to compile csvdownload.proto. What am I doing wrong here?

Any help in dealing with this issue would be greatly appreciated.


Solution

  • You must change your directory structure to something like this:

    /protobuf
    |-- /common
        |-- common.proto
    |-- /api
        |-- /service
            |-- csvdownload.proto
    

    also, I suggest you add a real package address for common.proto

    syntax = "proto3";
    package protobuf;
    
    option go_package = "myProject.com/proto/common"; // golang
    

    then you can import this common to your other protos like this.

    import "common/common.proto";
    

    the generating code is(it is the full request you want(I think))

    protoc --proto_path=../base_directory/protobuf/api/service/ --proto_path=../base_directory/protobuf/ --go_out=plugins=grpc:./the/generated/path/you/want/directory ../base_directory/protobuf/api/service/csvdownload.proto