mirror of
https://github.com/zeromicro/go-zero.git
synced 2026-05-07 23:20:00 +08:00
Example 03: Importing Proto from a Subdirectory
This example demonstrates importing a proto file from a subdirectory.
Proto Definition
Two proto files with different go_package values:
order.proto— Defines theOrderService, importscommon/types.proto.
option go_package = "example.com/demo/pb";
common/types.proto— Defines reusable pagination and sorting messages.
option go_package = "example.com/demo/pb/common";
order.proto imports common/types.proto from a subdirectory:
import "common/types.proto";
Note that the two files have different go_package values, so they compile into separate Go packages.
Generation Commands
First, initialize the output directory with a go.mod:
mkdir -p output && cd output && go mod init example.com/demo && cd ..
Then generate the code:
goctl rpc protoc order.proto \
--go_out=output \
--go-grpc_out=output \
--zrpc_out=output \
--go_opt=module=example.com/demo \
--go-grpc_opt=module=example.com/demo \
--module=example.com/demo \
-I .
Generated directory structure:
output/
├── etc
│ └── ordersvc.yaml
├── go.mod
├── internal
│ ├── config
│ │ └── config.go
│ ├── logic
│ │ ├── getorderlogic.go
│ │ └── listorderslogic.go
│ ├── server
│ │ └── orderserviceserver.go
│ └── svc
│ └── servicecontext.go
├── orderservice
│ └── orderservice.go
├── ordersvc.go
└── pb
├── common
│ └── types.pb.go
├── order.pb.go
└── order_grpc.pb.go
Key Points
- Two proto files have different
go_packagevalues, so they compile into separate Go packages (pb/andpb/common/). order.protoimportscommon/types.protofrom a subdirectory.- When imported protos have a different
go_package, goctl automatically generates cross-package imports. - The
-I .flag tells protoc to search from the current directory, enabling it to findcommon/types.proto.