### Define Proto Service and HTTP Annotations Source: https://docs.jzero.io/guide/proto Example of a proto file defining a service with request and response messages. It includes annotations for HTTP routing using google.api.http. ```proto syntax = "proto3"; package version; import "google/api/annotations.proto"; import "grpc-gateway/protoc-gen-openapiv2/options/annotations.proto"; option go_package = "./types/version"; message VersionRequest {} message VersionResponse { string version = 1; string goVersion = 2; string commit = 3; string date = 4; } service Version { rpc Version(VersionRequest) returns(VersionResponse) { option (google.api.http) = { get: "/version" }; }; } ``` -------------------------------- ### Install jzero from Source (Go) Source: https://docs.jzero.io/getting-started/install Installs jzero from its source code using the `go install` command. This method requires Go version 1.24.3 or higher. It also includes commands to check the jzero version and download dependencies. ```bash # Set domestic proxy (optional) # go env -w GOPROXY=https://goproxy.cn,direct go install github.com/jzero-io/jzero/cmd/jzero@latest # Get jzero version information jzero version # Automatically download dependent tools jzero check ``` -------------------------------- ### Template Structure Example Source: https://docs.jzero.io/guide/template Illustrates the typical file structure of a jzero template stored locally. It shows various directories and files with a '.tpl' extension, indicating they are template files used for code generation. ```bash $ tree ~/.jzero/templates/local/myapi └── app ├── Dockerfile.tpl ├── README.md.tpl ├── cmd │   ├── root.go.tpl │   ├── server.go.tpl │   └── version.go.tpl ├── desc │   ├── api │   │   ├── helloworld.api.tpl │   │   └── version.api.tpl │   └── swagger │   ├── helloworld.swagger.json.tpl │   ├── swagger.json.tpl │   └── version.swagger.json.tpl ├── etc │   └── etc.yaml.tpl ├── go.mod.tpl ├── internal │   ├── config │   │   └── config.go.tpl │   ├── custom │   │   └── custom.go.tpl │   ├── handler │   │   ├── helloworld │   │   │   └── helloworld_compact.go.tpl │   │   ├── routes.go.tpl │   │   └── version │   │   └── version.go.tpl │   ├── logic │   │   ├── helloworld │   │   │   └── create.go.tpl │   │   └── version │   │   └── version.go.tpl │   ├── middleware │   │   ├── middleware.go.tpl │   │   ├── response.go.tpl │   │   └── validator.go.tpl │   ├── svc │   │   ├── config.go.tpl │   │   ├── middleware.go.tpl │   │   └── servicecontext.go.tpl │   └── types │   ├── helloworld │   │   └── types.go.tpl │   ├── types.go.tpl │   └── version │   └── types.go.tpl ├── main.go.tpl └── plugins └── plugins.go.tpl ``` -------------------------------- ### Initialize Project with Custom Templates Source: https://docs.jzero.io/guide/template Creates a new project using a specified template. Templates can be sourced from a remote Git repository (with optional caching) or a local path. This allows for consistent project structures based on predefined templates. ```bash # Initialize project from a remote repository template jzero new project_name --remote repo_to_your_templates --branch template_branch # Initialize project from a remote repository template using cache jzero new project_name --remote repo_to_your_templates --branch template_branch --cache # Initialize project from a local template jzero new project_name --local template_name # Initialize project from a template located at a specific path jzero new project_name --home path_to_template ``` -------------------------------- ### Install Jzero Dependencies Source: https://docs.jzero.io/community/contribute Installs the necessary dependencies for Jzero after cloning the repository. This is a prerequisite for running and debugging the application. ```bash cd jzero go install ``` -------------------------------- ### Initialize API Project using Jzero CLI Source: https://docs.jzero.io/getting-started/new Initializes a new API project using the Jzero CLI with the 'api' frame. It includes steps for navigating to the project directory, downloading dependencies, and starting the server. Access to Swagger UI is also provided. ```bash jzero new your_project --frame api cd your_project # 下载依赖 go mod tidy # 启动服务端程序 go run main.go server # 访问 swagger ui http://localhost:8001/swagger ``` -------------------------------- ### Configure HTTP and RPC Middleware in Proto Services Source: https://docs.jzero.io/guide/proto Shows how to apply HTTP and RPC middleware to proto services and individual methods using jzero-specific options. Middleware can be applied at the service level or method level. ```proto import "jzero/api/http.proto"; import "jzero/api/zrpc.proto"; service User { option (jzero.api.http_group) = { middleware: "auth", }; rpc CreateUser(CreateUserRequest) returns(CreateUserResponse) { option (google.api.http) = { post: "/api/v1/user/create", body: "*" }; option (jzero.api.zrpc) = { middleware: "withValue1", }; }; rpc ListUser(ListUserRequest) returns(ListUserResponse) { option (google.api.http) = { get: "/api/v1/user/{username}/list", }; }; } ``` -------------------------------- ### Load Configuration with etcd in Go Source: https://docs.jzero.io/component/configcenter Shows how to initialize and use the configcenter with the etcd subscriber in Go. This enables fetching configuration from an etcd cluster. The example specifies etcd connection details (hosts) and the configuration key. Dependencies include the jzero configcenter and subscriber packages, and go-zero's sqlx. ```go package main import ( "fmt" "github.com/jzero-io/jzero/core/configcenter" "github.com/jzero-io/jzero/core/configcenter/subscriber" "github.com/zeromicro/go-zero/core/stores/sqlx" ) type Config struct { Sqlx sqlx.SqlConf } func main() { cc := configcenter.MustNewConfigCenter[Config]( configcenter.Config{Type: "yaml"}, subscriber.MustNewEtcdSubscriber(subscriber.EtcdConf{ Hosts: []string{"127.0.0.1:2379"}, Key: "jzero-admin", }), ) // 设置配置变更回调 cc.AddListener(func() {}) // Placeholder for actual callback // 获取配置 cfg, err := cc.GetConfig() if err != nil { panic(err) } // 必须获取配置 cfg = cc.MustGetConfig() fmt.Println(cfg) } ``` -------------------------------- ### Check jzero Version (Binary) Source: https://docs.jzero.io/getting-started/install Checks the installed jzero version after downloading and extracting the binary. Assumes the binary is placed in `$GOPATH/bin`. ```bash # Get jzero version information jzero version # Automatically download dependent tools jzero check ``` -------------------------------- ### Initialize RPC Project using Jzero CLI Source: https://docs.jzero.io/getting-started/new Initializes a new RPC project using the Jzero CLI with the 'rpc' frame. The process involves creating the project, changing the directory, downloading Go modules, and starting the server. ```bash jzero new your_project --frame rpc cd your_project # 下载依赖 go mod tidy # 启动服务端程序 go run main.go server ``` -------------------------------- ### Upgrade jzero Source: https://docs.jzero.io/getting-started/install Commands to upgrade the jzero installation. Users can upgrade to the latest version or a specific version using a commit hash or tag. ```bash # Upgrade to the latest version jzero upgrade # Upgrade to a specified version jzero upgrade --channel or ``` -------------------------------- ### Initialize Gateway Project using Jzero Docker Source: https://docs.jzero.io/getting-started/new Initializes a new Gateway project using Jzero via Docker. This Docker command creates a gateway project, downloads dependencies, and starts the server, offering a containerized way to set up gateway services. ```bash docker run --rm -v ${PWD}:/app ghcr.io/jzero-io/jzero:latest new your_project --frame gateway cd your_project # 下载依赖 go mod tidy # 启动服务端程序 go run main.go server # 访问 swagger ui http://localhost:8001/swagger ``` -------------------------------- ### Initialize Jzero Templates Source: https://docs.jzero.io/guide/template Initializes jzero templates from built-in or remote repositories to a local directory. It supports initializing to the default home directory or a specified output path. This command is crucial for setting up the template environment for project generation. ```bash # Initialize jzero built-in template to $HOME/.jzero/templates/$Version jzero template init # Initialize template to the current project's .template directory jzero template init --output .template # Initialize remote repository template to $HOME/.jzero/templates/remote jzero template init --branch gateway # Extend go-zero's template goctl template init --home .template/go-zero ``` -------------------------------- ### Initialize and Use Redis Cache in Go Source: https://docs.jzero.io/component/cache Demonstrates how to initialize a Redis cache connection using jzero.io's cache package. It shows setting up a default cache with a specific expiry and another with a cache prefix. The example also includes fetching data from the cache. ```go package main import ( "context" "fmt" "time" "github.com/jzero-io/jzero/core/configcenter" "github.com/jzero-io/jzero/core/configcenter/subscriber" "github.com/jzero-io/jzero/core/stores/cache" "github.com/pkg/errors" "github.com/zeromicro/go-zero/core/stores/redis" ) type Config struct { Redis redis.RedisConf } func main() { cc := configcenter.MustNewConfigCenter[Config]( configcenter.Config{Type: "yaml"}, subscriber.MustNewFsnotifySubscriber("etc/etc.yaml"), ) // 连接 redis rds, err := redis.NewRedis(cc.MustGetConfig().Redis) if err != nil { panic(err) } // 从 redis 新建缓存, 设置默认缓存时间 5 秒 redisCache := cache.NewRedisNode(rds, errors.New("cache not found"), cache.WithExpiry(time.Duration(5)*time.Second)) // 带 cachePrefix redisCache = cache.NewRedisNodeWithCachePrefix(rds, errors.New("cache not found"), "jzero:",cache.WithExpiry(time.Duration(5)*time.Second)) // 获取 key 为 name 的数据 var value string if err = redisCache.GetCtx(context.Background(), "name", &value); err != nil { panic(err) } fmt.Println(value) } ``` -------------------------------- ### Implement Proto Field Validation with buf.validate Source: https://docs.jzero.io/guide/proto Demonstrates how to use buf.validate for automatic field validation within proto messages. Supports built-in rules and custom CEL expressions. ```proto syntax = "proto3"; package versionpb; import "buf/validate/validate.proto"; option go_package = "./pb/versionpb"; // 使用内置规则 message CreateRequest { string email = 1 [(buf.validate.field).string.email = true]; int32 age = 2 [(buf.validate.field).int32.gt = 17]; string name = 3 [(buf.validate.field).string.min_len = 2]; } // cel 表达式, 支持自定义 message message GetRequest { int32 id = 1 [ (buf.validate.field).cel = { id: "id.length" message: "id must be greater than 0 and less than 100000" expression: "this > 0 && this < 100000" } ]; } ``` -------------------------------- ### Connect to SQL Database with jzero.io modelx (Go) Source: https://docs.jzero.io/component/modelx Demonstrates how to establish a SQL database connection using jzero.io's modelx package. It reads database configuration from a YAML file and initializes a connection pool. The example shows executing a simple 'SELECT 1' query to verify the connection. ```go package main import ( "context" "fmt" "github.com/jzero-io/jzero/core/configcenter" "github.com/jzero-io/jzero/core/configcenter/subscriber" "github.com/jzero-io/jzero/core/stores/modelx" "github.com/zeromicro/go-zero/core/stores/sqlx" ) type Config struct { Sqlx sqlx.SqlConf } func main() { cc := configcenter.MustNewConfigCenter[Config]( configcenter.Config{Type: "yaml"}, subscriber.MustNewFsnotifySubscriber("etc/etc.yaml"), ) sqlConn := modelx.MustNewConn(cc.MustGetConfig().Sqlx) // 连接数据库 ssqlConn := modelx.MustNewConn(cc.MustGetConfig().Sqlx) // 执行 sql result, err := sqlConn.ExecCtx(context.Background(), "select 1") if err != nil { panic(err) } fmt.Println(result) } ``` -------------------------------- ### Check jzero Version (Docker) Source: https://docs.jzero.io/getting-started/install Retrieves the jzero version information by running a Docker container. This is a convenient way to check the version without a local installation. ```bash # Get jzero version information docker run --rm ghcr.io/jzero-io/jzero:latest version ``` -------------------------------- ### Lint and Fix Code Source: https://docs.jzero.io/community/contribute Installs the golangci-lint tool and runs it to lint the code, automatically fixing common issues. This helps maintain code quality and identify potential bugs. ```bash go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest golangci-lint run --fix ``` -------------------------------- ### Configure YAML with Environment Variables in Go Source: https://docs.jzero.io/component/configcenter Illustrates how to use environment variables within a YAML configuration file for the jzero configcenter. This allows for dynamic configuration values to be injected at runtime. The example shows how to reference environment variables using the ${VAR_NAME:-default_value} syntax. ```yaml sqlx: # 从 DATASOURCE 获取 sqlx 的 datasource 配置, 未配置则为 jzero-admin.db datasource: "${DATASOURCE:-jzero-admin.db}" # 从 DRIVER_NAME 获取 sqlx 的 driverName 配置, 未配置则为 sqlite driverName: "${DRIVER_NAME:-sqlite}" ``` -------------------------------- ### Generate Go Model Registration Code (MySQL) Source: https://docs.jzero.io/guide/model This Go code demonstrates the automatically generated `model.go` file for registering database models. It imports generated model packages and provides a `NewModel` function to initialize them with a SQL connection. ```go // Code generated by jzero. DO NOT EDIT. package model import ( "github.com/eddieowens/opts" "github.com/jzero-io/jzero-admin/server/internal/model/manage_email" "github.com/jzero-io/jzero-admin/server/internal/model/manage_menu" "github.com/jzero-io/jzero-admin/server/internal/model/manage_role" "github.com/jzero-io/jzero-admin/server/internal/model/manage_role_menu" "github.com/jzero-io/jzero-admin/server/internal/model/manage_user" "github.com/jzero-io/jzero-admin/server/internal/model/manage_user_role" "github.com/jzero/core/stores/modelx" "github.com/zeromicro/go-zero/core/stores/sqlx" ) type Model struct { ManageEmail manage_email.ManageEmailModel ManageMenu manage_menu.ManageMenuModel ManageRole manage_role.ManageRoleModel ManageRoleMenu manage_role_menu.ManageRoleMenuModel ManageUser manage_user.ManageUserModel ManageUserRole manage_user_role.ManageUserRoleModel } func NewModel(conn sqlx.SqlConn, op ...opts.Opt[modelx.ModelOpts]) Model { return Model{ ManageEmail: manage_email.NewManageEmailModel(conn, op...), ManageMenu: manage_menu.NewManageMenuModel(conn, op...), ManageRole: manage_role.NewManageRoleModel(conn, op...), ManageRoleMenu: manage_role_menu.NewManageRoleMenuModel(conn, op...), ManageUser: manage_user.NewManageUserModel(conn, op...), ManageUserRole: manage_user_role.NewManageUserRoleModel(conn, op...), } } ``` -------------------------------- ### Add New API Plugin with jzero Source: https://docs.jzero.io/guide/serverless Commands to create a new API plugin for jzero. Supports creating a standalone Go module or integrating into an existing monorepo. The `serverless build` command compiles the plugin and integrates its routes into the main service. ```bash # Create a new simple API project jzero new simpleapi # Navigate into the project directory cd simpleapi # Create a new API plugin as an independent go module jzero new your_plugin --frame api --serverless # Create a new API plugin sharing the go module with the main service (monorepo) jzero new your_mono_plugin --frame api --serverless --mono # Execute serverless build to integrate plugin routes into the main service (plugins/plugins.go) jzero serverless build # Download dependencies go mod tidy # Build the main application go build ``` -------------------------------- ### Build Custom Jzero Template from Project Source: https://docs.jzero.io/guide/template Converts an existing project into a jzero template. This involves creating a new project, adding components, generating code, and then building the current project as a template. The built template can then be used to create new projects with the same structure and components. ```bash # Create a new API project jzero new simpleapi # Navigate into the project directory cd simpleapi # Add a new API component jzero add api helloworld # Generate code jzero gen # Build the current project as a template named 'myapi' jzero template build --name myapi # Use the newly built template to create a project jzero new mysimpleapi --local myapi # Push the template to a remote repository (e.g., GitHub) # git remote add origin # git push -u origin myapi ``` -------------------------------- ### Run jzero Code Generation Command Source: https://docs.jzero.io/guide/mongo This command executes the jzero code generation process based on the configured settings. Ensure your configuration file is correctly set up before running this command. ```bash jzero gen ``` -------------------------------- ### Configure SQL Database Connection (YAML) Source: https://docs.jzero.io/component/modelx Provides an example of a YAML configuration file for setting up a SQL database connection with jzero.io. It specifies the data source name and the driver name, allowing for easy adaptation to different database systems like SQLite, MySQL, or PostgreSQL. ```yaml sqlx: datasource: "jzero-admin.db" driverName: "sqlite" ``` -------------------------------- ### Generate Go Model Registration Code (Multi-Schema) Source: https://docs.jzero.io/guide/model This Go code illustrates the `model.go` file when multiple schemas are used, including a separate schema for logs. It defines distinct model groups for different schemas and provides corresponding `New` functions for initialization. ```go // Code generated by jzero. DO NOT EDIT. package model import ( "github.com/eddieowens/opts" "github.com/jzero/core/stores/modelx" "github.com/zeromicro/go-zero/core/stores/sqlx" "github.com/jzero-io/jzero-admin/server/internal/model/jzero-admin_log/operate_log" "github.com/jzero-io/jzero-admin/server/internal/model/manage_email" "github.com/jzero-io/jzero-admin/server/internal/model/manage_menu" "github.com/jzero-io/jzero-admin/server/internal/model/manage_role" "github.com/jzero-io/jzero-admin/server/internal/model/manage_role_menu" "github.com/jzero-io/jzero-admin/server/internal/model/manage_user" "github.com/jzero-io/jzero-admin/server/internal/model/manage_user_role" ) type JzeroAdminLogModel struct { OperateLog operate_log.OperateLogModel } type Model struct { ManageEmail manage_email.ManageEmailModel ManageMenu manage_menu.ManageMenuModel ManageRole manage_role.ManageRoleModel ManageRoleMenu manage_role_menu.ManageRoleMenuModel ManageUser manage_user.ManageUserModel ManageUserRole manage_user_role.ManageUserRoleModel } func NewModel(conn sqlx.SqlConn, op ...opts.Opt[modelx.ModelOpts]) Model { return Model{ ManageEmail: manage_email.NewManageEmailModel(conn, op...), ManageMenu: manage_menu.NewManageMenuModel(conn, op...), ManageRole: manage_role.NewManageRoleModel(conn, op...), ManageRoleMenu: manage_role_menu.NewManageRoleMenuModel(conn, op...), ManageUser: manage_user.NewManageUserModel(conn, op...), ManageUserRole: manage_user_role.NewManageUserRoleModel(conn, op...), } } func NewJzeroAdminLogModel(conn sqlx.SqlConn, op ...opts.Opt[modelx.ModelOpts]) JzeroAdminLogModel { return JzeroAdminLogModel{ OperateLog: operate_log.NewOperateLogModel(conn, op...), } } ``` -------------------------------- ### Uninstall Plugins with jzero Source: https://docs.jzero.io/guide/serverless Commands to remove plugins from a jzero project. `serverless delete` removes all plugins, disabling their route handling. The `--plugin` flag allows for the removal of specific plugins. Recompilation is necessary after uninstallation. ```bash # Uninstall all plugins, main service will no longer handle plugin routes jzero serverless delete # Uninstall a specific plugin jzero serverless delete --plugin # Recompile the application go build ``` -------------------------------- ### Upgrade and Generate Code with jzero CLI Source: https://docs.jzero.io/release/v1.1.1 This snippet shows the command-line interface (CLI) commands to upgrade the jzero project to version 1.1.1 and then regenerate code. Ensure you have the jzero CLI installed and configured. ```bash jzero upgrade --channel v1.1.1 jzero gen ``` -------------------------------- ### Configure PostgreSQL ORM Code Generation Source: https://docs.jzero.io/guide/model This configuration enables code generation for PostgreSQL using the `pgx` driver. It includes settings for caching, connecting to a remote PostgreSQL data source, ignoring specific columns, and selecting tables for model generation. ```yaml gen: model-driver: pgx # 是否生成带缓存的数据库代码 model-cache: true # 缓存表, 默认为 *(所有) model-cache-table: - manage_user # 是否使用远程 postgres 数据源生成代码 model-datasource: true # postgres 数据源配置 model-datasource-url: "postgres://root:123456@127.0.0.1:5432/jzero-admin" # Ignore columns while creating or updating rows, 默认为 create_at,created_at,create_time,update_at,updated_at,update_time model-ignore-columns: ["create_time", "update_time"] # 使用哪些 table, 默认为 *(所有) model-datasource-table: - manage_email - manage_menu - manage_role - manage_role_menu - manage_user - manage_user_role ``` -------------------------------- ### Build Delete Statement with Condition Chain in Go Source: https://docs.jzero.io/component/condition Illustrates deleting records using Jzero IO's condition chain builder. This method allows for more fluent construction of multiple conditions. It covers configuration loading, database connection, building a condition chain with options like `WithValueFunc` and `WithSkipFunc`, and then generating and executing the DELETE statement using `condition.BuildDelete` and `condition.BuildDeleteWithFlavor`. Dependencies are similar to the single condition example. ```go package main import ( "context" "fmt" "github.com/jzero-io/jzero/core/configcenter" "github.com/jzero-io/jzero/core/configcenter/subscriber" "github.com/jzero-io/jzero/core/stores/modelx" "github.com/zeromicro/go-zero/core/stores/sqlx" "github.com/huandu/go-sqlbuilder" "github.com/jzero-io/jzero/core/stores/condition" ) type Config struct { Sqlx sqlx.SqlConf } func main() { // 加载配置 cc := configcenter.MustNewConfigCenter[Config]( configcenter.Config{Type: "yaml"}, subscriber.MustNewFsnotifySubscriber("etc/etc.yaml"), ) // 连接 mysql 并返回 flavor sqlConn, flavor := modelx.MustNewConnAndSqlbuilderFlavor(cc.MustGetConfig().Sqlx) chain := condition.NewChain().Equal("name", "jzero", // WithValueFunc 比 value 优先级高 condition.WithValueFunc(func() any { return "jzero" }), // 是否跳过该条件 condition.WithSkip(false), // WithSkipFunc 优先级比 WithSkip 高 condition.WithSkipFunc( func() bool { return false }), ) // 设置全局 flavor(默认 mysql) sqlbuilder.DefaultFlavor = sqlbuilder.PostgreSQL statement, args := condition.BuildDelete(sqlbuilder.DeleteFrom("user"), chain.Build()...) fmt.Println(statement, args) // 使用特定 flavor statement, args = condition.BuildDeleteWithFlavor(flavor, sqlbuilder.DeleteFrom("user"), chain.Build()...) result, err := sqlConn.ExecCtx(context.Background(), statement, args) if err != nil { panic(err) } fmt.Println(result) } ``` -------------------------------- ### Initialize and Run Database Migrations (Go) Source: https://docs.jzero.io/component/migrate This Go code snippet demonstrates how to initialize the jzero.io migrate component and run all 'up' migration scripts. It reads database configuration from 'etc/etc.yaml' and uses the 'migrate' package for managing SQL migrations. Ensure the 'configcenter' and 'migrate' packages are imported. ```go package main import ( "github.com/jzero-io/jzero/core/configcenter" "github.com/jzero-io/jzero/core/configcenter/subscriber" "github.com/jzero-io/jzero/core/stores/migrate" "github.com/zeromicro/go-zero/core/stores/sqlx" ) type Config struct { Sqlx sqlx.SqlConf } func main() { cc := configcenter.MustNewConfigCenter[Config]( configcenter.Config{Type: "yaml"}, subscriber.MustNewFsnotifySubscriber("etc/etc.yaml", subscriber.WithUseEnv(true))) m, err := migrate.NewMigrate(cc.MustGetConfig().Sqlx) if err != nil { panic(err) } deffer m.Close() if err = m.Up(); err != nil { panic(err) } } ``` -------------------------------- ### Initialize Project with Optional Features (Model/Redis/Cache) Source: https://docs.jzero.io/getting-started/new Demonstrates initializing a Jzero project with specific optional features using the '--features' flag. This allows for pre-configuration of database (model), Redis, and cache functionalities. ```bash # 使用场景: 需要连接关系型数据库(model)且包含数据库缓存(cache), redis jzero new your_project --features model,cache,redis # 使用场景: 需要连接关系型数据库(model), redis jzero new your_project --features model,redis # 使用场景: 需要连接关系型数据库(model)且包含数据库缓存(cache) jzero new your_project --features model,cache # 使用场景: 需要连接关系型数据库(model) jzero new your_project --features model ``` -------------------------------- ### Load Configuration with fsnotify in Go Source: https://docs.jzero.io/component/configcenter Demonstrates how to initialize and use the configcenter with the fsnotify subscriber in Go. It shows loading configuration from a YAML file, supporting environment variables, and setting up listeners for configuration changes. Dependencies include the jzero configcenter and subscriber packages, and go-zero's sqlx. ```go package main import ( "fmt" "github.com/jzero-io/jzero/core/configcenter" "github.com/jzero-io/jzero/core/configcenter/subscriber" "github.com/zeromicro/go-zero/core/stores/sqlx" ) type Config struct { Sqlx sqlx.SqlConf } func main() { cc := configcenter.MustNewConfigCenter[Config]( configcenter.Config{Type: "yaml"}, subscriber.MustNewFsnotifySubscriber("etc/etc.yaml"), ) // 支持环境变量 cc = configcenter.MustNewConfigCenter[Config]( configcenter.Config{Type: "yaml"}, subscriber.MustNewFsnotifySubscriber("etc/etc.yaml", subscriber.WithUseEnv(true)), ) // 设置配置变更回调 cc.AddListener(func() {}) // Placeholder for actual callback // 获取配置 cfg, err := cc.GetConfig() if err != nil { panic(err) } // 必须获取配置 cfg = cc.MustGetConfig() fmt.Println(cfg) } ``` -------------------------------- ### Initialize Jzero Migration with Multi-Database Support (Go) Source: https://docs.jzero.io/component/migrate This Go code snippet demonstrates how to initialize the Jzero migration tool with support for multiple database drivers. It uses `configcenter` to load configuration and `migrate.WithSourceAppendDriver(true)` to enable driver-specific migration directories. ```go package main import ( "github.com/jzero-io/jzero/core/configcenter" "github.com/jzero-io/jzero/core/configcenter/subscriber" "github.com/jzero-io/jzero/core/stores/migrate" "github.com/zeromicro/go-zero/core/stores/sqlx" ) type Config struct { Sqlx sqlx.SqlConf } func main() { cc := configcenter.MustNewConfigCenter[Config]( configcenter.Config{Type: "yaml"}, subscriber.MustNewFsnotifySubscriber("etc/etc.yaml", subscriber.WithUseEnv(true))), ) m, err := migrate.NewMigrate(cc.MustGetConfig().Sqlx, migrate.WithSourceAppendDriver(true)) if err != nil { panic(err) } deffer m.Close() if err = m.Up(); err != nil { panic(err) } } ``` -------------------------------- ### Initialize API Project using Jzero Docker Source: https://docs.jzero.io/getting-started/new Initializes a new API project using Jzero via Docker. This command mounts the current directory to the container, creates the project, and then proceeds with dependency download and server startup. Swagger UI access is also shown. ```bash docker run --rm -v ${PWD}:/app ghcr.io/jzero-io/jzero:latest new your_project --frame api cd your_project # 下载依赖 go mod tidy # 启动服务端程序 go run main.go server # 访问 swagger ui http://localhost:8001/swagger ``` -------------------------------- ### SQL Migration - Initialization Script (Up) Source: https://docs.jzero.io/component/migrate This SQL script defines the 'up' migration for initializing the 'manage_user' table. It includes dropping the table if it exists and then creating it with specified columns, constraints, and an initial data insert. This script is executed when applying the migration. ```sql DROP TABLE IF EXISTS `manage_user`; CREATE TABLE `manage_user` ( `id` bigint NOT NULL AUTO_INCREMENT, `uuid` varchar(36) NOT NULL UNIQUE, `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, `username` varchar(30) NOT NULL, `password` varchar(100) NOT NULL, `nickname` varchar(30) NOT NULL, `gender` varchar(1) NOT NULL, `phone` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL, `status` varchar(1) NOT NULL, `email` varchar(100) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `uni_manage_user_username` (`username`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; INSERT INTO `manage_user` (`uuid`, `create_time`, `update_time`, `username`, `password`, `nickname`, `gender`, `phone`, `status`, `email`) VALUES ('1c2d3e4f-5a6b-7c8d-9e0f-1a2b3c4d5e6f','2024-10-24 09:45:00','2024-10-31 09:40:13','admin','123456','超级管理员','1','','1',''); ``` -------------------------------- ### Get Current Database Migration Version using jzero CLI Source: https://docs.jzero.io/guide/migrate Command to retrieve the current version of the database migrations using the jzero command-line interface. This helps in understanding the current state of the database schema. ```bash jzero migrate version ``` -------------------------------- ### Upgrade and Generate Code with jzero CLI Source: https://docs.jzero.io/release/v1.1.3 This snippet shows the command-line interface commands to upgrade the jzero project to version 1.1.3 and then regenerate necessary code. Ensure the jzero CLI is installed and accessible in your environment. ```bash jzero upgrade --channel v1.1.3 jzero gen ``` -------------------------------- ### Initialize Gateway Project using Jzero CLI Source: https://docs.jzero.io/getting-started/new Initializes a new Gateway project using the Jzero CLI with the 'gateway' frame. This project type supports both gRPC and HTTP interfaces. The initialization includes dependency management and server startup, with Swagger UI access provided. ```bash jzero new your_project --frame gateway cd your_project # 下载依赖 go mod tidy # 启动服务端程序 go run main.go server # 访问 swagger ui http://localhost:8001/swagger ``` -------------------------------- ### Initialize RPC Project using Jzero Docker Source: https://docs.jzero.io/getting-started/new Initializes a new RPC project using Jzero via Docker. This method uses a Docker container to create the project, manage dependencies, and run the server, similar to the CLI approach but within a containerized environment. ```bash docker run --rm -v ${PWD}:/app ghcr.io/jzero-io/jzero:latest new your_project --frame rpc cd your_project # 下载依赖 go mod tidy # 启动服务端程序 go run main.go server ``` -------------------------------- ### Configure Multi-Source PostgreSQL ORM Code Generation Source: https://docs.jzero.io/guide/model This configuration allows Jzero ORM to generate code from multiple PostgreSQL data sources. It specifies multiple data source URLs and includes tables from different schemas, such as `jzero-admin_log.operate_log`. ```yaml gen: model-driver: postgres # 是否生成带缓存的数据库代码 model-cache: true # 缓存表, 默认为 *(所有) model-cache-table: - manage_user # 是否使用远程 postgres 数据源生成代码 model-datasource: true # postgres 数据源配置 model-datasource-url: - "postgres://root:123456@127.0.0.1:5432/jzero-admin" - "postgres://root:123456@127.0.0.1:5432/jzero-admin_log" # Ignore columns while creating or updating rows, 默认为 create_at,created_at,create_time,update_at,updated_at,update_time model-ignore-columns: ["create_time", "update_time"] # 使用哪些 table, 默认为 *(所有) model-datasource-table: - manage_email - manage_menu - manage_role - manage_role_menu - manage_user - manage_user_role - jzero-admin_log.operate_log ``` -------------------------------- ### Configure jzero for MongoDB Code Generation Source: https://docs.jzero.io/guide/mongo This configuration block specifies the types of MongoDB models to generate and caching options. It allows you to define the 'mongo-type' for model generation and 'mongo-cache' to enable or disable caching, with 'mongo-cache-type' to specify which types should be cached. ```yaml gen: # 指定 mongo type mongo-type: ["user", "role", "menu"] # 是否需要缓存 mongo-cache: true # 指定哪些类型需要缓存 mongo-cache-type: - user ``` -------------------------------- ### Initialize jzero Skills Source: https://docs.jzero.io/getting-started/skills Initializes the jzero skills tool. By default, it outputs to the `~/.claude/skills` folder. You can specify a different output directory using the `--output` flag, such as the current project's `.claude/skills` folder. ```bash # Default output to ~/.claude/skills folder jzero skills init # Input to the current project jzero skills init --output .claude/skills ``` -------------------------------- ### Configure MySQL Model Generation with Caching Source: https://docs.jzero.io/guide/model This configuration block specifies settings for generating database models using MySQL. It enables caching for specific tables and defines columns to ignore during create/update operations. The `jzero gen` command utilizes these settings. ```yaml gen: # mysql or postgres, 默认为 mysql model-driver: mysql # 是否生成带缓存的数据库代码 model-cache: true # 缓存表, 默认为 *(所有) model-cache-table: - manage_user # schema model-schema: jzero-admin # Ignore columns while creating or updating rows, 默认为 create_at,created_at,create_time,update_at,updated_at,update_time model-ignore-columns: ["create_time", "update_time"] ``` -------------------------------- ### YAML Configuration for SQL Database Source: https://docs.jzero.io/component/condition This snippet shows a typical YAML configuration file for setting up SQL database connections within the jzero framework. It specifies the data source path and the driver name, essential for initializing database connections. ```yaml sqlx: datasource: "jzero-admin.db" driverName: "sqlite" ``` -------------------------------- ### System User API Endpoints (Compact Handler) Source: https://docs.jzero.io/guide/api Demonstrates how to group multiple system user-related endpoints into a single handler file using `compact_handler: true`. ```APIDOC ## GET /api/v1/system/user/getUser ### Description Retrieves system user information. ### Method GET ### Endpoint /api/v1/system/user/getUser ### Parameters #### Query Parameters (No query parameters defined in the example) ### Request Example ``` (No specific request example provided for this endpoint) ``` ### Response #### Success Response (200) (Response details not specified in the example) #### Response Example ```json (Response example not provided) ``` ## GET /api/v1/system/user/deleteUser ### Description Deletes a system user. ### Method GET ### Endpoint /api/v1/system/user/deleteUser ### Parameters #### Query Parameters (No query parameters defined in the example) ### Request Example ``` (No specific request example provided for this endpoint) ``` ### Response #### Success Response (200) (Response details not specified in the example) #### Response Example ```json (Response example not provided) ``` ``` -------------------------------- ### Configure Multi-Source MySQL ORM Code Generation Source: https://docs.jzero.io/guide/model This configuration allows Jzero ORM to generate code from multiple MySQL data sources. It lists multiple data source URLs and specifies tables from different schemas, including a new table `jzero-admin_log.operate_log`. ```yaml gen: model-driver: mysql # 是否生成带缓存的数据库代码 model-cache: true # 缓存表, 默认为 *(所有) model-cache-table: - manage_user # 是否使用远程 mysql 数据源生成代码 model-datasource: true # mysql 数据源配置 model-datasource-url: - "root:123456@tcp(127.0.0.1:3306)/jzero-admin" - "root:123456@tcp(127.0.0.1:3306)/jzero-admin_log" # Ignore columns while creating or updating rows, 默认为 create_at,created_at,create_time,update_at,updated_at,update_time model-ignore-columns: ["create_time", "update_time"] # 使用哪些 table, 默认为 *(所有) model-datasource-table: - manage_email - manage_menu - manage_role - manage_role_menu - manage_user - manage_user_role - jzero-admin_log.operate_log ``` -------------------------------- ### Add Proto File using jzero CLI Source: https://docs.jzero.io/getting-started/add Command to add a new proto description file within the 'desc/proto' directory. It enables the generation of gRPC server and client code based on the defined proto services. You can specify nested service names. ```bash # Service 为 Test jzero add proto test # Service 为 TestTest1 jzero add proto test/test1 ``` -------------------------------- ### Build Delete Statement with Conditions in Go Source: https://docs.jzero.io/component/condition Demonstrates how to build and execute a DELETE SQL statement using Jzero IO's condition builder. It loads configuration, establishes a database connection, defines conditions, and uses `condition.BuildDelete` and `condition.BuildDeleteWithFlavor` to generate and execute the statement. Dependencies include `context`, `fmt`, `configcenter`, `subscriber`, `modelx`, `sqlx`, `go-sqlbuilder`, and `condition`. ```go package main import ( "context" "fmt" "github.com/jzero-io/jzero/core/configcenter" "github.com/jzero-io/jzero/core/configcenter/subscriber" "github.com/jzero-io/jzero/core/stores/modelx" "github.com/zeromicro/go-zero/core/stores/sqlx" "github.com/huandu/go-sqlbuilder" "github.com/jzero-io/jzero/core/stores/condition" ) type Config struct { Sqlx sqlx.SqlConf } func main() { // 加载配置 cc := configcenter.MustNewConfigCenter[Config]( configcenter.Config{Type: "yaml"}, subscriber.MustNewFsnotifySubscriber("etc/etc.yaml"), ) // 连接 mysql 并返回 flavor sqlConn, flavor := modelx.MustNewConnAndSqlbuilderFlavor(cc.MustGetConfig().Sqlx) conditions := condition.New(condition.Condition{ // 操作的字段 Field: "name", // 操作 Operator: condition.Equal, // 字段的值 Value: "jzero", // ValueFunc 优先级比 Skip 高 ValueFunc: func() any { return "jzero" }, // 是否跳过该条件 Skip: false, // SkipFunc 优先级比 Skip 高 SkipFunc: func() bool { return false }, }) // 设置全局 flavor(默认 mysql) sqlbuilder.DefaultFlavor = sqlbuilder.PostgreSQL statement, args := condition.BuildDelete(sqlbuilder.DeleteFrom("user"), conditions...) fmt.Println(statement, args) // 使用特定 flavor statement, args = condition.BuildDeleteWithFlavor(flavor, sqlbuilder.DeleteFrom("user"), conditions...) result, err := sqlConn.ExecCtx(context.Background(), statement, args) if err != nil { panic(err) } fmt.Println(result) } ``` -------------------------------- ### Configure MySQL ORM Code Generation Source: https://docs.jzero.io/guide/model This configuration enables code generation for MySQL. It specifies the MySQL driver, enables caching for specific tables, and connects to a remote MySQL data source. It also defines columns to ignore during updates and lists the tables to be included in the model generation. ```yaml gen: model-driver: mysql # 是否生成带缓存的数据库代码 model-cache: true # 缓存表, 默认为 *(所有) model-cache-table: - manage_user # 是否使用远程 mysql 数据源生成代码 model-datasource: true # mysql 数据源配置 model-datasource-url: "root:123456@tcp(127.0.0.1:3306)/jzero-admin" # Ignore columns while creating or updating rows, 默认为 create_at,created_at,create_time,update_at,updated_at,update_time model-ignore-columns: ["create_time", "update_time"] # 使用哪些 table, 默认为 *(所有) model-datasource-table: - manage_email - manage_menu - manage_role - manage_role_menu - manage_user - manage_user_role ``` -------------------------------- ### Add SQL File using jzero CLI Source: https://docs.jzero.io/getting-started/add Command to add a new SQL description file within the 'desc/sql' directory. This command is used to generate database-related code, such as table definitions, based on the provided table name. ```bash # table 名为 test jzero add sql test ```