protoc编译时是否可自动导入grpc.pb.go中的生成结构体?分目录生成proto结构体与gRPC接口的导入问题
I've run into this exact scenario before when splitting proto-generated structs and gRPC service interfaces into different directories. The key is to use the --go-grpc_opt flag with either the module parameter (for modular projects) or the M parameter (to explicitly map proto files to their import paths) to tell the gRPC plugin where to find your proto structs.
Option 1: Use Module-Wide Configuration (Recommended for Go Modules)
If your project uses Go modules, this is the cleanest approach. Specify your module path in both --go_opt and --go-grpc_opt to ensure all generated code uses consistent import paths:
protoc \ --go_out=internal/proto --go_opt=module=github.com/your-username/your-project \ --go-grpc_out=internal/grpc --go-grpc_opt=module=github.com/your-username/your-project \ path/to/your/mymodel.proto
This tells the protoc plugins that your project's root module is github.com/your-username/your-project, so the gRPC-generated code will automatically import the proto structs from github.com/your-username/your-project/internal/proto—no manual edits needed.
Option 2: Explicitly Map Individual Proto Files
If you only need to configure a single proto file (or want granular control), use the M parameter in --go-grpc_opt to map your proto file to its target import path:
protoc \ --go_out=internal/proto \ --go-grpc_out=internal/grpc \ --go-grpc_opt=Mmymodel.proto=github.com/your-username/your-project/internal/proto \ mymodel.proto
The format here is M<proto-filename>=<full-import-path>. This directly instructs the gRPC plugin to import the structs from internal/proto when generating mymodel_grpc.pb.go.
Key Notes for Success
- Double-check that your
go.modfile's module name matches the path you use in the commands above. - After running the command, verify the import statement in
mymodel_grpc.pb.go—it should point to yourinternal/protodirectory with the correct module prefix. - For multiple proto files, you can add multiple
Mparameters (one per proto) or stick with the module-wide approach to avoid repetition.
内容的提问来源于stack exchange,提问作者Tigran Babajanyan

