jzero is a template-driven code generation framework built on go-zero that automates microservice development through declarative specification files. The framework processes .api files (HTTP REST APIs), .proto files (gRPC services), and .sql files (database schemas) to generate production-ready Go code with handlers, business logic stubs, data access layers, and client SDKs.
The system architecture follows an orchestration pattern: the CLI binary cmd/jzero/main.go53-177 initializes a Cobra command tree that delegates to specialized generation engines in cmd/jzero/internal/command/gen/ which invoke external tools (goctl, protoc) and apply AST-based post-processing to enforce jzero conventions. Templates are resolved from cmd/jzero/internal/embeded/ or custom sources via cmd/jzero/internal/pkg/templatex/
This document provides a high-level overview of jzero's architecture, core subsystems, and design principles. For installation instructions, see Installation and Getting Started. For detailed subsystem documentation, refer to their respective sections in this wiki.
Sources: cmd/jzero/main.go1-177 go.mod1-3 go.mod22 README.md14-32
jzero addresses three primary use cases:
Project Initialization: The cmd/jzero/internal/command/new/new.go command scaffolds complete microservice projects with three frame types (api, rpc, gateway) and optional features (model, redis). Templates are resolved from embedded resources cmd/jzero/.template/ local cache ~/.jzero/templates/, or remote Git repositories.
Code Generation: The cmd/jzero/internal/command/gen/gen.go command discovers specification files in desc/api/, desc/proto/, and desc/sql/, invokes goctl/protoc for base code generation, then applies post-processing in cmd/jzero/internal/command/gen/genapicode.go and cmd/jzero/internal/command/gen/genrpccode.go to remove suffixes, update imports, compact handlers, and generate unified registration files in internal/handler/routes.go and internal/server/server.go.
Schema Management: The cmd/jzero/internal/command/migrate/migrate.go command wraps golang-migrate/migrate v4.19.1 to apply versioned database migrations from desc/sql_migration/, tracking state in the schema_migrations table.
The framework maintains ecosystem compatibility by delegating code generation to external tools (goctl, protoc) and applying enhancements through AST manipulation rather than replacing go-zero's generators. This enables incremental adoption and interoperability with existing go-zero projects.
Sources: cmd/jzero/internal/command/new/new.go cmd/jzero/internal/command/gen/gen.go cmd/jzero/internal/command/gen/genapicode.go cmd/jzero/internal/command/migrate/migrate.go go.mod11 README.md14-33
jzero implements a four-tier configuration precedence system loaded during cmd/jzero/main.go149-176 The global config.C struct (defined in cmd/jzero/internal/config/config.go) is populated via Viper:
--style, --home, --remote have highest priorityJZERO_ (e.g., JZERO_GEN_STYLE=gozero) override file-based config.jzero.yaml in project root or subdirectories (e.g., third_party/.jzero.yaml).jzero.env.yaml defines template variables expanded via github.com/a8m/envsubst v1.4.3Configuration Loading Sequence:
This layered design enables local development workflows (primarily YAML-based) and CI/CD automation (primarily environment variable-based) without code changes.
Sources: cmd/jzero/main.go120-176 cmd/jzero/internal/config/config.go go.mod7
jzero provides three filtering mechanisms implemented in cmd/jzero/internal/command/gen/gen.go:
| Mechanism | CLI Flag | Implementation | Use Case |
|---|---|---|---|
| Git-based | --git-change | Parses git status --short output, filters by M or A status | Regenerate only changed services |
| Explicit paths | --desc path1,path2 | Direct file path matching via slice contains | Generate specific subsystems |
| Ignore patterns | --desc-ignore pattern1,pattern2 | Glob pattern exclusion via filepath.Match | Skip third-party or archived specs |
The discovery phase combines these filters before invoking goctl. For example, in a project with 100 .proto files, --git-change regenerates only modified services, reducing generation time from minutes to seconds. The filtered file list is passed to goctl api go --api <file> or goctl rpc protoc <file>.
Sources: cmd/jzero/internal/command/gen/gen.go README.md20-21
Templates are resolved via a waterfall precedence chain in cmd/jzero/internal/embeded/embeded.go:
| Priority | Source | Resolution | Use Case |
|---|---|---|---|
| 1 | --home /path flag | Direct filesystem read | Project-specific overrides |
| 2 | --local <name> flag | ~/.jzero/templates/local/<name> | User-built templates |
| 3 | --remote <url> flag | Git clone to ~/.jzero/templates/remote/ | Enterprise/shared templates |
| 4 | Embedded | go:embed directive in cmd/jzero/main.go42-44 | Default jzero templates |
Template Resolution Flow:
The cmd/jzero/internal/command/template/init.go command extracts embedded templates to the filesystem for customization. Template variables include {{.Module}}, {{.GoVersion}}, {{.Style}}, {{.Features}}, and custom values from --register-tpl-val.
Sources: cmd/jzero/main.go42-44 cmd/jzero/internal/embeded/embeded.go cmd/jzero/internal/command/template/init.go cmd/jzero/internal/pkg/templatex/
jzero generates database-agnostic models via the goctl model command, then applies runtime driver selection:
| Database | Driver | go.mod Dependency | Config Key |
|---|---|---|---|
| MySQL | mysql | github.com/go-sql-driver/mysql v1.9.3 | DataSource[i].Driver: "mysql" |
| PostgreSQL | postgres/pgx | github.com/jackc/pgx/v5 v5.7.6 | DataSource[i].Driver: "postgres" |
| SQLite | sqlite | modernc.org/sqlite v1.42.2 | DataSource[i].Driver: "sqlite" |
| MongoDB | (mongo driver) | Separate generator | MongoDataSource config |
The model layer in internal/model/ uses github.com/zeromicro/go-zero v1.9.3's sqlx.SqlConn interface, allowing the same generated model code to work across SQL dialects by changing the connection string and driver name in the configuration file.
Sources: docs/src/guide/model.md8-24 go.mod13 go.mod22-23 go.mod43
The jzero CLI follows a command pattern where cmd/jzero/main.go64-109 initializes a Cobra root command that delegates to subcommands:
Lifecycle Hooks:
Run() functionsSources: cmd/jzero/main.go53-177 cmd/jzero/internal/command/check/check.go36-196 cmd/jzero/internal/desc/desc.go
The cmd/jzero/internal/command/gen/gen.go command orchestrates a multi-stage pipeline that transforms specification files into production code:
Pipeline Stages:
--git-change, --desc, and --desc-ignore flagsgoctl api go, goctl rpc protoc, goctl model mysql ddl with discovered filesroutes.go, server.go, model.go, clientset.go) that wire all components togetherSources: cmd/jzero/internal/command/gen/gen.go cmd/jzero/internal/command/gen/genapicode.go cmd/jzero/internal/command/gen/genrpccode.go cmd/jzero/internal/command/gen/genmodel.go cmd/jzero/internal/command/gen/genregister.go
This diagram shows the relationships between major jzero subsystems and their external dependencies:
Key Dependencies:
goctl integration, dst v0.27.3 for AST post-processingSources: go.mod1-115 cmd/jzero/main.go1-177 cmd/jzero/internal/command/gen/gen.go cmd/jzero/internal/pkg/mod/mod.go1-127
The following example traces how a single API specification transforms into executable code:
Input Specification (desc/api/user.api):
syntax = "v1"
service user {
@handler GetUser
get /user/:id (GetUserRequest) returns (GetUserResponse)
}
type GetUserRequest {
Id int64 `path:"id"`
}
type GetUserResponse {
Id int64 `json:"id"`
Name string `json:"name"`
}
Command Execution:
Generated Files:
Handler (internal/handler/user/getuserhandler.go → internal/handler/user/getuser.go after post-processing):
goctl api goLogic (internal/logic/user/getuserlogic.go → internal/logic/user/getuser.go after post-processing):
goctl api goTypes (internal/types/user/types.go):
goctl api gogo_package annotation via cmd/jzero/internal/command/gen/genapicode.goGetUserRequest and GetUserResponse structsRoutes (internal/handler/routes.go):
RegisterHandlers() function that registers all HTTP routesjzero gen to include new handlersFile Transformation Pipeline:
Sources: cmd/jzero/internal/command/gen/gen.go cmd/jzero/internal/command/gen/genapicode.go cmd/jzero/internal/command/gen/genregister.go
All code generation in jzero operates through templates. Default templates embody best practices for go-zero applications, while custom templates enable organizations to enforce internal standards.
Template resolution follows a precedence order:
--home flag~/.jzero/templates/localThis allows per-project, per-user, and framework-level customization.
Sources: README.md29 docs/src/README.md26
jzero extends go-zero without modifying it. The framework:
goctl as a code generation engine under the hoodThis design ensures teams can gradually adopt jzero or use it alongside existing go-zero tooling.
Sources: README.md30 docs/src/README.md27
jzero does not mandate specific infrastructure choices. Projects can:
The configcenter component exemplifies this philosophy by supporting both file-based (fsnotify) and etcd-based configuration subscribers.
Sources: README.md32 docs/src/README.md29 docs/src/component/configcenter.md7-127
jzero supports team collaboration through:
plugins/ directory (see Plugin Architecture)Sources: README.md31 docs/src/README.md28
jzero is built on Go 1.24.3 and organized as a single module (github.com/jzero-io/jzero) with the following key dependencies:
| Dependency | Version | Purpose | Used By |
|---|---|---|---|
| go-zero | v1.9.3 | Microservices framework (REST, gRPC, sqlx, config) | Generated code runtime |
| golang-migrate | v4.19.1 | Database schema version management | cmd/jzero/internal/command/migrate/ |
| go-sqlbuilder | v1.38.2 | Fluent SQL query builder | condition.Chain in generated models |
| pgx/v5 | v5.7.6 | PostgreSQL driver with connection pooling | Generated model runtime |
| sqlite | v1.42.2 | Pure-Go SQLite (no CGO) | Generated model runtime |
| cobra | v1.10.1 | CLI framework | cmd/jzero/main.go64-146 |
| viper | v1.21.0 | Configuration management | cmd/jzero/internal/config/ |
| dst | v0.27.3 | AST manipulation for post-processing | cmd/jzero/internal/command/gen/genapicode.go |
| envsubst | v1.4.3 | Environment variable substitution in templates | cmd/jzero/internal/pkg/templatex/ |
| sprig/v3 | v3.3.0 | Template function library | Template rendering |
| fsnotify | v1.9.0 | File system event monitoring | Config center hot-reload |
External Tools (installed via jzero check):
| Tool | Version | Installation | Purpose |
|---|---|---|---|
| goctl | v1.9.2 | go install github.com/zeromicro/go-zero/tools/goctl@v1.9.2 | Code generation engine |
| protoc | v32.0 | Downloaded from GitHub releases | Protocol buffer compiler |
| protoc-gen-go | v1.36.8 | go install google.golang.org/protobuf/cmd/protoc-gen-go@v1.36.8 | Go proto plugin |
| protoc-gen-go-grpc | v1.5.1 | go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@v1.5.1 | gRPC proto plugin |
| protoc-gen-openapiv2 | v2.27.2 | go install github.com/grpc-ecosystem/grpc-gateway/v2/protoc-gen-openapiv2@v2.27.2 | OpenAPI generation |
Sources: go.mod1-115 cmd/jzero/internal/command/check/check.go28-34
jzero is structured as a single Go module with two primary directories:
CLI Package (cmd/jzero/):
| Directory | Purpose | Key Symbols |
|---|---|---|
main.go | CLI entry point, Cobra initialization | rootCmd, Execute(), InitConfig() |
internal/command/ | Command implementations | new.GetCommand(), gen.GetCommand(), add.GetCommand() |
internal/command/gen/ | Code generation logic | GenApicode(), GenRpccode(), GenModel(), GenSwagger() |
internal/config/ | Configuration management | config.C global struct, InitConfig() |
internal/embeded/ | Embedded template resolution | Template (go:embed), Home path resolution |
internal/pkg/templatex/ | Template rendering | ParseTemplate(), template function registry |
internal/pkg/mod/ | Go module inspection | GetGoMod(), GetParentPackage() |
internal/desc/ | Specification file parsing | GetFrameType(), ParseApiFile(), ParseProtoFile() |
.template/ | Default embedded templates | frame/api/, frame/rpc/, go-zero/api/, go-zero/model/ |
Runtime Library Package (root level):
| Directory | Purpose | Key Symbols |
|---|---|---|
condition/ | SQL query builder | Chain, Condition, Equal(), In(), BuildSelectWithFlavor() |
configcenter/ | Dynamic configuration | FileSubscriber, EtcdSubscriber, AddListener() |
restc/ | HTTP client utilities | Post(), Get(), Put(), Delete() with context support |
The CLI package generates code that imports the runtime library package. For example, generated models import github.com/jzero-io/jzero/condition for query building.
Sources: go.mod1-3 cmd/jzero/main.go1-177 condition/ configcenter/
jzero supports three primary project frames, each tailored for different service architectures:
HTTP-only service with REST endpoints defined in .api files. Generates:
internal/handler/internal/logic/internal/server/Sources: docs/src/getting-started/new.md24-53
gRPC-only service with service definitions in .proto files. Generates:
internal/server/internal/logic/Sources: docs/src/getting-started/new.md55-79
Hybrid service supporting both HTTP and gRPC protocols. Combines features of both API and RPC frames:
.api files.proto filesSources: docs/src/getting-started/new.md82-114
All frame types support optional features specified during project creation:
model: Generates SQL database models with CRUD operationsredis: Includes Redis configuration and cache integrationmodel,redis: Combines both database and cache layersExample: jzero new myproject --frame gateway --features model,redis
Sources: docs/src/getting-started/new.md116-134
The jzero CLI provides the following commands, implemented via Cobra in cmd/jzero/:
| Command | Implementation | Purpose | Output |
|---|---|---|---|
jzero new <name> | internal/new/ | Scaffold new project from templates | main.go, internal/, .jzero.yaml |
jzero add api <name> | internal/add/ | Create API specification file | desc/api/<name>.api |
jzero add proto <name> | internal/add/ | Create proto service definition | desc/proto/<name>.proto |
jzero add sql <name> | internal/add/ | Create SQL schema file | desc/sql/<name>.sql |
jzero gen | internal/gen/ | Generate all server code | internal/handler/, internal/logic/, internal/model/ |
jzero gen swagger | internal/gen/genswagger.go | Generate OpenAPI spec | desc/swagger/swagger.json |
jzero gen zrpcclient | internal/gen/genzrpcclient.go | Generate gRPC client SDK | <service>client/clientset.go |
jzero migrate up | internal/migrate/ | Apply pending migrations | Updates schema_migrations table |
jzero migrate down | internal/migrate/ | Revert last migration | Rolls back schema changes |
jzero template init | internal/template/ | Extract embedded templates | ~/.jzero/templates/local/ |
jzero serverless build | internal/serverless/ | Build plugin from plugins/ | plugins/<name>.so |
jzero format | internal/format/ | Format Go code with gosimports | In-place file updates |
jzero check | internal/check/ | Install required tools | Installs goctl, protoc |
For detailed command architecture, hook system, and configuration loading, see CLI Architecture.
Sources: cmd/jzero/ architecture Diagram 2
jzero integrates with a growing ecosystem of tools and projects:
.api files, navigation from specs to logic, and inline code generationSources: README.md70-75 docs/src/ecosystem/jzero-intellij.md1-28 docs/src/ecosystem/jzero-admin.md1-22
The jzero-io/examples repository contains automatically generated and validated example projects covering all supported frame types and feature combinations. These examples are regenerated on every main branch push via GitHub Actions.
Sources: README.md68 Diagram 6 from high-level architecture
To begin using jzero:
go install github.com/jzero-io/jzero/cmd/jzero@latestjzero check (installs required dependencies)jzero new myproject --frame apijzero add api users or jzero add proto authjzero gengo run main.go serverFor detailed installation instructions and Docker usage, see Installation and Getting Started.
Sources: README.md36-52 docs/src/README.md31-64
Refresh this wiki
This wiki was recently refreshed. Please wait 7 days to refresh again.