golang / protobuf

Go support for Google's protocol buffers
BSD 3-Clause "New" or "Revised" License
9.64k stars 1.58k forks source link

How to append the user's package name into the generated go source. #1565

Closed Kidsunbo closed 9 months ago

Kidsunbo commented 9 months ago

Hi, I would like to reuse some of the proto files among different Golang projects. For a simple example, I have a project with such structure:

.
├── base
│   └── base.proto
└── user
    ├── service.proto
    └── user.proto

The base.proto defines some basic message used by all the other folders. So I use import "base.base.proto" in other proto files. I was told to add go_package option to give the package name of the generated Golang source files. But if I use ./user for user.proto and service.proto and ./base for base.proto. The generated user.pb.go will import ./base which can't be resolved by compiler. I use the following command to generate the proto files.

protoc --proto_path=./pb --go_out=proto_gen --go-grpc_out=proto_gen  \
    --go_opt=paths=import --go-grpc_opt=paths=import \
    user/service.proto user/user.proto base/base.proto

So the question is, how could I make the generated source file import the right package name. For example, importing <my_project_package_name>/pb/base rather than ./base in user.pb.go.

neild commented 9 months ago

The go_package option should contain the full import path of the Go package. So, for your example:

option go_package = "<my_project_package_name>/pb/base";
Kidsunbo commented 9 months ago

The go_package option should contain the full import path of the Go package. So, for your example:

option go_package = "<my_project_package_name>/pb/base";

But what if the other project wants to use the proto file? Change the name manually everytime?

neild commented 9 months ago

The simplest approach is to generate the Go package once and make it a dependency of whatever other packages require it.

If you do need to generate code in various Go packages from the same .proto source file (not recommended), you can set the Go package on the protoc command line with something like --go_opt=Mbase/base.proto=<my_project_package_name>/pb/base. See https://protobuf.dev/reference/go/go-generated/#package for details.

Kidsunbo commented 9 months ago

The simplest approach is to generate the Go package once and make it a dependency of whatever other packages require it.

If you do need to generate code in various Go packages from the same .proto source file (not recommended), you can set the Go package on the protoc command line with something like --go_opt=Mbase/base.proto=<my_project_package_name>/pb/base. See https://protobuf.dev/reference/go/go-generated/#package for details.

Thanks, that's helpful.