gogrpcprotobuf-go

I want to generate protobufs from proto files from cmd without using "option go_package "


I have to generate protobuf file from a proto file which import another proto file. One another requirement, this has to be generated by cmd (by not defining "option go_package" in the proto file).


Solution

  • Let's say you have 3 files foo.proto, poo.proto and zoo.proto. The file foo.proto imports a message struct from poo.proto and zoo.proto. You need to write the command in a specific order which puts foo.proto(importing from other) first and poo.proto(giving import to other) and zoo.proto(giving import to other) after that.

    Here is the command to generate protobufs without defining option go_package

    protoc --proto_path=./ --go_out=./pb --go-grpc_out=./pb
    --go_opt=Mfoo.proto=./ --go-grpc_opt=Mfoo.proto=./
    --go_opt=Mpoo.proto=./ --go-grpc_opt=Mpoo.proto=./
    --go_opt=Mzoo.proto=./ --go-grpc_opt=Mzoo.proto=./
    foo.proto goo.proto zoo.proto
    

    Notice the M before filename, it replaces option go_package in your code

    foo.proto

    syntax = "proto3";
    import "goo.proto";
    import "zoo.proto";
    
    service Foo {
        rpc FooRPC(PooMessage) returns (ZooMessage) {}
    }
    

    poo.proto

    syntax = "proto3";
    
    message PooMessage {
        string body = 1;
    }
    

    zoo.proto

    syntax = "proto3";
    
    message ZooMessage {
        string body = 1;
    }