kratos proto command provides subcommands for working with Protocol Buffer files, including adding new proto templates, generating client code, and generating server implementations.
Usage
Subcommands
add
Add a new proto API template
client
Generate client code from proto files
server
Generate server implementations from proto files
kratos proto add
Add a new proto API template file with boilerplate service definition.Usage
Arguments
path- The hierarchical path for the proto file (e.g.,helloworld/v1/hello.proto)
Description
Creates a new proto file with a basic service template. The path must be hierarchical (contain at least one/).
Examples
- Package declaration based on the path
- Go package option configured
- Java package option configured
- Basic service definition
The proto path must be hierarchical. Single-level paths like
hello.proto are not allowed.kratos proto client
Generate client code from proto files using protoc.Usage
Arguments
proto-file-or-directory- Path to a single.protofile or a directory containing proto files
Flags
Path to search for proto dependencies. Can be overridden by setting the
KRATOS_PROTO_PATH environment variable.Description
Generates Go code from proto files using protoc with multiple plugins:protoc-gen-go- Standard Go proto compilerprotoc-gen-go-grpc- gRPC service codeprotoc-gen-go-http- Kratos HTTP transport codeprotoc-gen-go-errors- Kratos error definitionsprotoc-gen-openapi- OpenAPI specification
kratos upgrade to install them.
Generated Files
For a proto fileapi/helloworld/v1/greeter.proto, the following files are generated:
greeter.pb.go- Proto message definitionsgreeter_grpc.pb.go- gRPC service definitionsgreeter_http.pb.go- HTTP transport bindingsgreeter_errors.pb.go- Error definitionsgreeter.openapi.yaml- OpenAPI specification
Examples
Generate from Single File
Generate from Directory
.proto files (excluding third_party/).
Custom Proto Path
Using Environment Variable
kratos proto server
Generate server implementation stubs from proto service definitions.Usage
Arguments
proto-file- Path to the proto file containing service definitions
Flags
Directory where the generated service implementation files will be created.
Description
Generates Go service implementation stubs from proto service definitions. For each service in the proto file, it creates a Go file with:- Service struct definition
- Constructor function
- Method stubs for all RPC methods
- Proper imports and package declarations
- Unary RPC
- Server streaming
- Client streaming
- Bidirectional streaming
Examples
Basic Usage
internal/service/greeter.go with implementation stubs.
Custom Target Directory
Generated Code Structure
For a proto file with aGreeter service:
The command will not overwrite existing service files. If a file already exists, it will be skipped with a warning message.
Complete Workflow Example
Related Commands
kratos new- Create a new project with proto structurekratos upgrade- Update proto generation tools