Overview
Kratos code generation includes:- protoc-gen-go-http: Generates HTTP server and client code from protobuf with Google API annotations
- protoc-gen-go-errors: Generates type-safe error definitions from enums
- Standard protoc plugins for gRPC and protobuf messages
Installation
Install
protoc from protobuf releases:# macOS
brew install protobuf
# Linux
apt install -y protobuf-compiler
# Verify installation
protoc --version
# Standard Go protobuf plugin
go install google.golang.org/protobuf/cmd/protoc-gen-go@latest
# gRPC plugin
go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest
# Kratos HTTP plugin
go install github.com/go-kratos/kratos/cmd/protoc-gen-go-http/v2@latest
# Kratos errors plugin
go install github.com/go-kratos/kratos/cmd/protoc-gen-go-errors/v2@latest
# OpenAPI plugin (optional)
go install github.com/google/gnostic/cmd/protoc-gen-openapi@latest
Using protoc-gen-go-http
The HTTP plugin generates server routing and client code from protobuf definitions.Basic Usage
Generate HTTP bindings from a protobuf file:Generated Code Structure
For this protobuf definition:api/helloworld/v1/greeter.proto
greeter_http.pb.go with:
HTTP Method Mapping
The plugin supports all HTTP methods:Path Variable Binding
The plugin automatically binds path variables to request fields:Body Binding
Control how request bodies are bound:Response Body Customization
Customize the response body:Using protoc-gen-go-errors
The errors plugin generates type-safe error constructors from enum definitions.Basic Usage
Generate error definitions:Define Error Enums
Create an errors protobuf file:api/helloworld/v1/errors.proto
Generated Error Code
The plugin generates helper functions:api/helloworld/v1/errors.pb.go
Using Generated Errors
Use the generated functions in your service:Makefile Integration
Create a Makefile for easy code generation:Makefile
Configuration File
Use a configuration file for complex setups:buf.gen.yaml
Best Practices
Version Control
Commit generated code to version control for reproducibility
CI/CD Integration
Run code generation in CI to ensure it’s always up to date
Code Reviews
Review generated code changes to catch API breaking changes
Documentation
Generate OpenAPI specs for API documentation
Troubleshooting
Import not found errors
Import not found errors
Ensure third_party directory contains Google API protos:
Plugin not found
Plugin not found
Verify plugins are in PATH and executable:
Generated code has wrong imports
Generated code has wrong imports
Check the go_package option in your proto files matches your module structure.
Next Steps
Service Implementation
Implement your generated service interfaces
Testing
Learn how to test generated code