Skip to content
CAI
Software that uses CAICheck a score

zeromicro/go-zero

63.1

Adequate · 24 September 2026

62.1k

lines of production code

Go

primary language

4

measurements over time

CAI band scale
CAI trend line
CAI lens gauges

What this system is

This system is a comprehensive Go microservice framework that provides infrastructure for building distributed applications, including HTTP and gRPC servers, service discovery, and database access layers. It features a code generation CLI tool that scaffolds services and clients for multiple languages from API and protobuf definitions. The framework emphasizes observability through OpenTelemetry integration, structured logging, and Prometheus metrics, while offering resilience patterns like circuit breaking and rate limiting.

How it got here

2020 — Core modernization and codegen expansion

115 changes.

The project underwent a massive architectural overhaul, stripping out legacy HTTP, RPC, and queue infrastructure while migrating the core to Go generics, context-aware APIs, and OpenTelemetry. Simultaneously, the goctl tooling was significantly expanded to support new language targets like Dart, Java, and Kotlin, alongside enhanced SQL and API generation capabilities.

2021–2022 — goctl CLI modernization and MongoDB support

55 changes.

This period focused on modernizing the goctl CLI by migrating to the Cobra framework, introducing a robust upgrade mechanism, and adding comprehensive environment management utilities. Significant new features included MongoDB model generation using the official Go driver v2, PostgreSQL support for SQL models, and a new HTTP gateway for routing to gRPC services. The work also strengthened the core framework with context-aware logging, configurable middleware chaining, and improved service discovery compatibility for newer Go versions.

2023–2026 — goctl parser rewrite and testing infrastructure

13 changes.

This period focused on overhauling the goctl tooling by replacing its API parser with a new AST-based implementation and rewriting the Swagger generator for better type support. Concurrently, the project expanded its testing capabilities by introducing dedicated packages for trace, log, and regression testing, while also adding new features like gateway generation and continuous profiling.

Features

Add JSON5 configuration support

The encoding package now supports JSON5 configuration files. Users can provide configuration in JSON5 format, which allows for comments, trailing commas, and unquoted keys. The system automatically converts these files to standard JSON, ensuring compatibility while rejecting values not supported by standard JSON, such as Infinity and NaN.

internal/encoding · high confidence

Add Java code generation for goctl API definitions

Introduces a new Java generator to the goctl toolchain, allowing users to generate Java HTTP packet and model classes from Go API specifications. The implementation adds a \JavaCommand\ entry point and supporting logic in \gen.go\, \gencomponents.go\, and \genpacket.go\ to parse API definitions and produce Java source files using embedded templates (\component.tpl\, \packet.tpl\, etc.). Generated code includes model classes extending \HttpData\ or \HttpResponseData\ and packet classes extending \HttpPacket\, with support for request/response types, path parameters, and primitive type mapping.

tools/goctl/api/javagen · high confidence

Add PostgreSQL model generation support

The goctl SQL model generator now supports PostgreSQL databases. This change introduces new model files (\infoschemamodel.go\ and \postgresqlmodel.go\) that query PostgreSQL system catalogs (such as \information\_schema\ and \pg\_catalog\) to extract table and column metadata. It includes a type mapping layer (\p2m\) that converts PostgreSQL-specific data types (e.g., \int8\, \uuid\, \timestamptz\) into their MySQL-equivalent types for consistent Go struct generation, and handles PostgreSQL-specific features like serial types and identity columns for auto-increment fields.

tools/goctl/model/sql/model · high confidence

Add SortedMap collection and file downloader utility

The goctl tool now includes a new \SortedMap\ type in the \collection\ package that maintains key-value pairs in insertion order, supporting operations like setting expressions, retrieving values with defaults, and iterating with early exit. Additionally, a \downloader\ package has been added to provide a simple utility for downloading files from URLs to the local filesystem.

tools/goctl/pkg/collection · high confidence

Add context-aware panic recovery function

The rescue package now includes a new RecoverCtx function that allows panic recovery to be performed with a specific context. This enables logging panic details with context-aware loggers, providing better traceability for errors in concurrent or request-scoped operations compared to the existing Recover function.

core/rescue · high confidence

Add customizable file naming format utility

A new \FileNamingFormat\ function has been added to the \tools/goctl/util/format\ package, allowing users to define custom file naming styles by specifying format strings that include 'GO' and 'ZERO' markers. This utility parses input strings (typically snake\_case) and transforms them into the desired case style (e.g., camelCase, PascalCase) with configurable prefixes, suffixes, and separators, enabling flexible code generation naming conventions.

tools/goctl/util/format · high confidence

Add gateway sample generation capability

The goctl tool now supports generating a sample gateway project structure. Running the new gateway command creates a basic Go application with a main entry point and a default configuration file (gateway.yaml), providing a starting point for users to build API gateways.

tools/goctl/gateway · high confidence

Add goctl API documentation generator

Introduces a new \docgen\ tool that parses \.api\ files and generates corresponding Markdown documentation. The tool walks the specified directory for API definitions, extracts route details (method, URI, request/response types), and renders them into structured Markdown files using an embedded template, including inline Go struct definitions for request and response bodies.

tools/goctl/api/docgen · high confidence

Add goctl API plugin support

Users can now extend goctl by writing custom plugins that process API specifications. The new \plugin\ package provides a CLI command (\goctl api plugin\) to execute external binaries (locally installed or downloaded via URL) and pass them structured API data via JSON. A demo plugin is included to illustrate how to consume the parsed API spec and configuration.

tools/goctl/plugin · high confidence

Add goctl Kotlin code generation support

The goctl tool now supports generating Kotlin client code from API definitions. This change introduces a new \ktgen\ module that includes a Cobra-based CLI command (\KtCommand\) to parse \.api\ files and generate Kotlin source files. The generated code includes a base HTTP client (\BaseApi.kt\) using Kotlin coroutines and a specific API interface file containing suspend functions for each defined route, handling JSON serialization via Gson and providing callbacks for success, failure, and completion events.

tools/goctl/api/ktgen · high confidence

Add goctl bug command for GitHub issue submission

The \goctl bug\ command is now available, allowing users to quickly open a pre-filled GitHub issue template for the zeromicro/go-zero repository. When executed, it automatically gathers and includes the current operating system, architecture, goctl version, and Go runtime version in the issue body, streamlining the bug reporting process.

tools/goctl/bug · high confidence

Add goctl env command for environment checking and installation

Users can now use the \goctl env\ command to verify and manage the Go development environment required by goctl. The new \check\ subcommand scans for essential dependencies like \protoc\, \protoc-gen-go\, and \protoc-gen-go-grpc\, reporting their status and offering to install missing tools interactively or via the \--install\ flag. The \install\ subcommand provides a direct way to install these dependencies, while the \write\ subcommand allows writing environment variables. This centralizes environment setup and validation within the goctl CLI.

tools/goctl/env · high confidence

Add goctl environment inspection and protoc-gen-go-grpc installation

The goctl tool now includes an \env\ command to inspect the runtime environment, specifically supporting the installation and version checking of the \protoc-gen-go-grpc\ plugin. This change introduces logic to cache and install the gRPC Go plugin binary, allowing users to verify its presence and version directly through goctl.

tools/goctl/pkg/goctl, tools/goctl/pkg/protocgengogrpc · high confidence

Add goctl environment utility for locating toolchain binaries

The goctl tool now includes a new environment utility package that provides functions to locate essential development binaries such as the Go compiler, protoc, protoc-gen-go, and protoc-gen-go-grpc. This utility automatically handles platform-specific executable suffixes (e.g., .exe on Windows) and checks for the presence of these tools in standard system paths, enabling goctl to verify and utilize the required toolchain for code generation tasks.

tools/goctl/util/env · high confidence

Add goctl quickstart command for scaffolding API and RPC services

The \goctl quickstart\ command is now available to scaffold and run a complete Go-Zero project structure. It supports two modes: 'mono' for a single API service and 'micro' for an API service with an integrated zRPC service. The command initializes a project directory, generates necessary configuration files (API, RPC, YAML configs), creates template code for handlers and logic, and automatically runs \go mod tidy\ and starts the service, providing a streamlined way to begin a new project.

tools/goctl/quickstart · high confidence

Add goctl upgrade command

Users can now run the \goctl upgrade\ command to update the goctl tool to the latest version. This new command, implemented using the Cobra CLI framework, executes \go install github.com/zeromicro/go-zero/tools/goctl@latest\ to fetch and install the most recent release.

tools/goctl/upgrade · high confidence

Add internal dev server for health, metrics, and profiling

An internal HTTP server is now available to expose application observability endpoints. When enabled via configuration, it serves health checks at the configurable health path (default /healthz) with a custom response, Prometheus metrics at the configurable metrics path (default /metrics), and Go pprof profiling endpoints at /debug/pprof/. The server listens on a configurable host and port (default 6060) and is started asynchronously in the background.

internal/devserver · high confidence

Added RPC example projects demonstrating single and multiple service generation

The \tools/goctl/example\ directory now includes two complete RPC service examples: \hello\ (a single service) and \hi\ (multiple services with grouped RPCs). These examples provide generated Go code, Protobuf definitions, configuration files, and shell scripts (\single\_rpc\_service\_generate.sh\ and \multiple\_rpc\_service\_generate.sh\) that demonstrate how to use the \goctl\ tool to generate RPC clients and servers, including support for generating multiple services from a single proto file.

tools/goctl/example · high confidence

Added Repr utility for consistent value string representation

The core/lang package now includes a Repr function that converts any value into a standardized string representation. This utility handles various types including primitives (integers, floats, booleans, strings), byte slices, errors, and types implementing the fmt.Stringer interface, ensuring consistent output across the application.

core/lang · high confidence

Added SQL schema examples for user and student tables

A new example SQL file (user.sql) has been added to the goctl SQL model tools, providing reference schema definitions for 'user' and 'student' tables. This includes column definitions, data types, constraints, and indexes, serving as a template for users generating database models.

tools/goctl/model/sql/example/sql · high confidence

Added automatic protoc binary installation and management

The goctl tool now includes a new package to handle the installation and verification of the Protocol Buffers compiler (protoc). This change introduces logic to automatically download the correct protoc binary (version 3.19.4) for Linux, macOS, and Windows (32/64-bit) from GitHub releases, cache it, and verify its presence and version. This simplifies the setup process for users by removing the need to manually install protoc before using goctl features that depend on it.

tools/goctl/pkg/protoc · high confidence

Added file matching and string utility helpers

The \tools/goctl/model/sql/util\ package now includes new utility functions to support model generation workflows. \MatchFiles\ enables globbing pattern matching for SQL files (e.g., \\*.sql\), allowing users to select multiple files via patterns rather than explicit paths. \TrimNewLine\ cleans up string inputs by removing carriage returns and newlines, while \TrimStringSlice\ filters out empty entries from string lists. These utilities improve the flexibility and robustness of file selection and data processing within the SQL model generation tool.

tools/goctl/model/sql/util · high confidence

Added gRPC error to HTTP status code conversion

The \rest/internal/errcode\ package now includes utilities to map gRPC error codes to standard HTTP status codes. This allows the REST layer to translate gRPC errors into appropriate HTTP responses (e.g., mapping \codes.Unauthenticated\ to 401 Unauthorized or \codes.NotFound\ to 404 Not Found), improving interoperability for services that bridge gRPC and HTTP.

rest/internal/errcode · high confidence

Added goctl RPC example documentation and translations

Added comprehensive documentation and example code for the goctl RPC generator, covering basic services, sibling and subdirectory proto imports, transitive imports, multiple services, well-known types, and external proto imports. The examples are provided in English, Chinese, and Korean to support a wider range of users.

tools/goctl/rpc/example · high confidence

Added goctl quickstart IDL templates and configuration files

Introduced a new set of IDL (Interface Definition Language) templates and configuration files for the goctl quickstart feature. This includes \api.yaml\ and \apilogic.tpl\ for defining a simple ping API service, \greet.api\ and \greet.proto\ for service definitions, \rpc.yaml\ for RPC configuration, and \svc.tpl\ for service context generation. These files provide the foundational structure for generating quickstart Go services with both API and RPC capabilities.

tools/goctl/quickstart/idl · high confidence

Added helpers to extract Span and Trace IDs from context

The internal/trace package now provides SpanIDFromContext and TraceIDFromContext functions, allowing users to retrieve the current span and trace identifiers from a Go context. These utilities simplify access to OpenTelemetry tracing data by safely returning empty strings when no active span is present, and are covered by unit tests verifying both populated and empty context scenarios.

internal/trace · high confidence

Added in-memory Redis test helper

A new \redistest\ package has been introduced to simplify testing Redis-dependent code by providing helper functions (\CreateRedis\ and \CreateRedisWithClean\) that spin up an in-memory Redis server using \miniredis\. This allows developers to run unit tests against a real Redis protocol implementation without requiring an external Redis instance.

core/stores/redis/redistest · high confidence

Added mock deposit service for testing

A new mock implementation of the deposit functionality has been added to the internal mock package. This includes the protocol buffer definitions (DepositRequest and DepositResponse) and a gRPC server implementation that simulates deposit operations by validating the amount and introducing a delay proportional to the deposit value, allowing developers to test deposit-related logic without a real backend.

internal/mock · high confidence

Added trace test helpers for in-memory exporter setup

A new \tracetest\ package provides a \NewInMemoryExporter\ helper that configures an in-memory OpenTelemetry tracer provider for use in tests. This allows test code to easily capture and inspect trace data without affecting the global tracing configuration, with automatic cleanup handled via test lifecycle hooks.

core/trace/tracetest · high confidence

Configuration loading now supports environment variable expansion and JSON5 format

The configuration loader in core/conf now supports environment variable substitution in configuration files when the UseEnv() option is passed to Load, LoadConfig, LoadProperties, or MustLoad. Additionally, JSON5 files (.json5) are now accepted alongside JSON, YAML, TOML, and properties files, allowing for comments, trailing commas, and unquoted keys. The LoadProperties function also respects the UseEnv() option for .properties files. These changes enhance flexibility in managing configuration values across different environments and formats.

core/conf · high confidence

Continuous CPU profiling with Pyroscope integration

The internal profiling package now supports continuous profiling by integrating with Pyroscope. Users can configure the profiling server address, authentication credentials, and specific profile types (CPU, goroutines, memory, mutex, block) via the Config struct. The system automatically monitors CPU usage against a configurable threshold and starts/stops profiling sessions at defined intervals, uploading data to the specified server.

internal/profiling · high confidence

Cross-platform shell command execution utility

A new \execx\ package has been introduced to provide a unified interface for executing shell commands across macOS, Linux, and Windows. This utility abstracts away OS-specific command interpreters (using \sh\ for Unix-like systems and \cmd.exe\ for Windows), allowing the \goctl\ tool to run scripts reliably on different operating systems while handling standard input, output, and error streams consistently.

tools/goctl/rpc/execx · high confidence

Initial TypeScript API client generation support

The \goctl\ tool now includes a new \tsgen\ module that generates TypeScript client code from Go API definitions. This feature introduces a command-line interface (powered by Cobra) to produce a reusable \gocliRequest.ts\ utility for handling HTTP requests, TypeScript interfaces for API types and parameters, and handler functions that wrap the API calls. Users can now automatically generate type-safe frontend client code directly from their Go API specs.

tools/goctl/api/tsgen · high confidence

Internal HTTP client now supports logging and metrics interception

The internal HTTP client implementation has been updated to support request interception, introducing built-in logging and metrics collection. Users benefit from automatic logging of HTTP request methods, URLs, status codes, and durations (logging errors for non-2xx responses), as well as the collection of request duration histograms and status code counters for observability.

rest/httpc/internal · high confidence

Introduce P2C (Power of Two Choices) load-balancing strategy for gRPC

The zrpc package now includes a new p2c balancer (registered as "p2c\_ewma") that implements the Power of Two Choices algorithm with EWMA-based latency tracking. This allows gRPC clients to distribute traffic more evenly across healthy backend instances by sampling two random connections and selecting the one with lower calculated load, improving request distribution entropy compared to random or round-robin strategies.

zrpc/internal/balancer/p2c · high confidence

Introduce SQL DDL parser for goctl model generation

The \tools/goctl/model/sql/parser\ package is added to parse MySQL DDL files into Go structures, enabling the \goctl model\ command to generate code from SQL schema definitions. The parser handles primary keys, unique indexes, and field metadata, while enforcing constraints such as rejecting joint primary keys and preventing crashes on unique keys with nil fields. A corresponding test suite validates parsing of plain text, SELECT statements, and CREATE TABLE statements, ensuring correct extraction of table names, primary keys, and unique index mappings.

tools/goctl/model/sql/parser · high confidence

Introduce goctl API template generation with embedded templates

The \goctl api\ command now supports generating a starter API template file. This change introduces the \apigen\ package which embeds a default \api.tpl\ template using Go's \embed\ feature. The generated template includes basic structure for requests, responses, and service definitions, with placeholders for git user information. Users can now create a new API definition file using the \goctl api\ command, which will generate a scaffolded \.api\ file with TODO comments for customization.

tools/goctl/api/apigen · high confidence

Introduce goctl MongoDB model generation

The \goctl\ tool now supports generating MongoDB data models. This change adds the \tools/goctl/model/mongo/generate\ package, which provides the core logic to generate model files, custom model files, type definitions, and error handling code based on provided templates. The generator supports configuration options such as cache prefixes and an 'easy' declaration flag, allowing users to scaffold their MongoDB data access layer directly from the command line.

tools/goctl/model/mongo/generate · high confidence

Introduce goctl api new command with module-aware service scaffolding

Users can now generate a complete Go API service scaffold using the \goctl api new\ command. This new capability creates the standard project directory structure (including \etc\, \internal/handler\, \internal/logic\, etc.), generates a starter \.api\ definition file, and writes a \go.mod\ file. The command supports specifying a custom Go module name via the \--module\ flag, ensuring generated imports are correct, and allows configuring the output style and remote template sources.

tools/goctl/api/new · high confidence

Introduce goctl command for generating MongoDB data models

Users can now use the \goctl model mongo\ command to automatically generate Go code for MongoDB data access layers. This new feature supports generating models with optional caching (via the \--cache\ flag and configurable key prefix), allows for simplified collection naming (via the \--easy\ flag), and enables remote template fetching (via \--remote\ and \--branch\). The generated code utilizes the \monc\ package for cached operations and \mon\ for error definitions, providing standard CRUD methods (Insert, FindOne, Update, Delete) tailored for MongoDB documents.

tools/goctl/model/mongo · high confidence

Introduce goctl config command and model type mapping defaults

The goctl tool now includes a new \config\ command with \init\ and \clean\ subcommands to manage the \goctl.yaml\ configuration file, which stores settings like file naming formats. Additionally, the system introduces a default configuration for model code generation that explicitly maps database types (such as PostgreSQL's \numeric\, \bigint\, and \decimal\) to specific Go types (e.g., \float64\, \int64\) and their nullable counterparts, ensuring consistent type generation for model code.

tools/goctl/config · high confidence

Introduce goctl docker command for automated Dockerfile generation

Users can now run \goctl docker\ to automatically generate a Dockerfile for their Go service. The command accepts flags to specify the entry Go file, the base image (defaulting to scratch), the listening port, and the timezone. It intelligently detects the project structure, locating the \etc/\ directory relative to the Go file to include configuration files in the image, and generates a multi-stage build optimized for size.

tools/goctl/docker · high confidence

Introduce goctl environment configuration management

The goctl tool now includes a dedicated environment management module that initializes and persists configuration settings such as home directory, cache location, debug mode, and experimental feature flags. This module automatically detects the operating system and architecture, reads existing configurations from a local file, and provides APIs to query or modify these settings, ensuring consistent environment state across goctl operations.

tools/goctl/pkg/env · high confidence

Introduce goctl migrate command for upgrading to zeromicro/go-zero

A new \migrate\ command is added to goctl to help users upgrade their projects from the legacy \github.com/tal-tech/go-zero\ module to the new \github.com/zeromicro/go-zero\ module. The command automatically updates the \go.mod\ file by removing the old dependency and adding the new one, rewrites import statements in Go source files to reflect the new module path, and runs \go mod tidy\. It supports specifying a target version (defaulting to v1.3.0) and provides verbose output and signal handling for cancellation on Unix-like systems.

tools/goctl/migrate · high confidence

Introduce goctl version management and comparison logic

The goctl tool now includes an internal version management system that exposes the current build version (1.10.2) and provides a utility to compare version strings. This allows the tool to determine if the installed version is newer than a target version, supporting semantic versioning with pre-release tags (alpha, beta, etc.), which is essential for update checks and compatibility validation.

tools/goctl/internal/version · high confidence

Introduce internal CORS middleware with configurable origins and headers

Added a new internal CORS handler and middleware in rest/internal/cors that automatically sets standard cross-origin headers (Allow-Origin, Allow-Methods, Allow-Headers, etc.) and supports configuring allowed origins, including wildcard (\*) and subdomain matching. The middleware allows callers to inject custom headers via a callback function, and a separate NotAllowedHandler provides a customizable response for disallowed origins.

rest/internal/cors · high confidence

Introduce internal gRPC resolver implementations for direct, discovery, etcd, and Kubernetes endpoints

The \zrpc/resolver/internal\ package now provides the concrete implementations for the gRPC resolver schemes used by the RPC client. This includes a \directBuilder\ for static endpoint lists, a \discovBuilder\ that leverages the core discovery subscriber for dynamic service lists, an \etcdBuilder\ that reuses the discovery logic for etcd-based resolution, and a \kubeBuilder\ that watches Kubernetes EndpointSlices to resolve in-cluster services. The \kubeBuilder\ specifically handles port detection by reading from EndpointSlices when not explicitly provided and supports a \no\_k8s\ build tag to exclude Kubernetes dependencies and reduce binary size. A \subset\ utility limits the number of addresses returned to 32 to prevent excessive state updates, and \RegisterResolver\ wires these builders into the gRPC resolver registry.

zrpc/resolver/internal · high confidence

Introduce new Dart API code generator with null-safety and path parameter support

The \goctl\ tool now includes a new Dart code generator (\tools/goctl/api/dartgen\) that produces Flutter-compatible Dart code from API definitions. This generator supports null-safe Dart syntax, correctly handles URL path parameters in route functions, and respects \omitempty\ JSON tags by applying default empty values for non-nullable types. It also supports nested structs, map types, and form tags, and automatically formats the generated Dart code using the \dart format\ command.

tools/goctl/api/dartgen · high confidence

Introduce new HTTP gateway for routing to gRPC and HTTP upstreams

Adds a new gateway component that allows HTTP requests to be routed to upstream gRPC services or other HTTP services. The gateway supports configuration via YAML, including explicit route mappings and proto descriptor sets for gRPC reflection, and exposes a \Server\ struct with options to add custom middlewares and dialers.

gateway · high confidence

Introduce rest/httpc for governed HTTP client requests

The new rest/httpc package provides a structured way to make HTTP requests with built-in governance. It includes a \Do\ function for sending requests with automatic marshaling of data into path, form, header, and JSON body fields, while explicitly rejecting bodies for GET and HEAD methods. A \Service\ interface and \NewService\ constructor allow creating named HTTP clients that integrate with the circuit breaker pattern to handle failures gracefully. Additionally, the package offers a \Parse\ function to easily decode HTTP responses into structs, handling both headers and JSON bodies, and automatically injects OpenTelemetry tracing context into outgoing requests.

rest/httpc · high confidence

Introduce structured logging with global/context fields and sensitive data masking

The logx package now supports attaching structured key-value fields to log entries via the new AddGlobalFields function for application-wide context and ContextWithFields for request-scoped context, allowing trace IDs or user identifiers to be automatically included in all logs. Additionally, a new Sensitive interface enables automatic masking of confidential data (such as passwords) in log output when implementing types implement the MaskSensitive method, improving security posture for sensitive information handling.

core/logx · high confidence

Introduction of Redis-backed RPC authentication

The \zrpc/internal/auth\ package now provides an \Authenticator\ that validates gRPC requests by checking \app\ and \token\ metadata against a Redis store, utilizing an in-memory cache for performance. A corresponding \Credential\ helper allows clients to attach these credentials to outgoing requests and parse them from incoming contexts. This change introduces a new behavioral capability for securing RPC traffic via Redis-based validation, replacing the previous \rpcx\ module location.

zrpc/internal/auth · high confidence

Introduction of colored console output for goctl

The goctl tool now provides colored console output for success, info, debug, warning, and error messages, enhancing readability. This change introduces a new \console\ package that wraps standard output with color formatting using the \github.com/gookit/color\ library. It also includes support for IntelliJ IDEA plugin logging via a separate \ideaConsole\ implementation that prefixes messages with tags like \[SUCCESS\] or \[ERROR\]. Users will see colored logs by default when running goctl commands.

tools/goctl/util/console · high confidence

New Go utility helpers for module path resolution and code formatting

The goctl tool now includes a new \golang\ package providing utilities to assist with Go project scaffolding. This adds functions to locate the GOBIN directory, format Go source code, and resolve parent package paths relative to a module root. These helpers support the generation of correct import paths and module structures when creating new Go projects or templates.

tools/goctl/pkg/golang · high confidence

New I/O utilities and modernization of core/iox

The core/iox package introduces new capabilities for input/output handling, including a pipe-based stdin/stdout redirection utility (RedirectInOut), a byte-limited tee reader (LimitTeeReader), and a limited duplicate reader (LimitDupReadCloser). Existing functions have been updated to use the standard library's io and os packages instead of the deprecated io/ioutil, and error checking has been modernized to use errors.Is for better compatibility with error wrapping. Additionally, the BufferPool now safely handles nil inputs during Put operations.

core/iox · high confidence

New ParseHeaders utility for HTTP header parsing

Added a new \ParseHeaders\ function in \rest/internal/encoding/parser.go\ that allows parsing HTTP request headers into struct fields using tags. This utility supports single values, multiple values (arrays), and type conversion (e.g., string to int), enabling more flexible header extraction in REST handlers.

rest/internal/encoding · high confidence

New and updated client interceptors for timeout, tracing, and metrics

The zrpc client now includes dedicated interceptors for timeout control, OpenTelemetry tracing, circuit breaking, and Prometheus metrics. Users can now set per-call timeouts via the new WithCallTimeout option or configure a global default, while the new DurationInterceptor logs slow RPC calls and allows disabling request/response body logging for specific methods. Tracing has been updated to use OpenTelemetry for both unary and streaming calls, and the Prometheus interceptor now exposes more granular duration buckets and uses the Milliseconds method for metric reporting.

zrpc/internal/clientinterceptors · high confidence

New concurrency primitives and context-aware safety in core/threading

This update introduces a new StableRunner that guarantees messages are processed and retrieved in the order they were pushed, which is useful for scenarios like Kafka consumers requiring parallel processing with ordered output. It also adds context-aware panic recovery functions (RunSafeCtx and GoSafeCtx) to the threading package, allowing safe goroutine execution with context cancellation support. Additionally, the TaskRunner now supports immediate task scheduling via ScheduleImmediately, which returns an error if the runner is busy, and includes a Wait method to ensure all scheduled tasks have completed.

core/threading · high confidence

New configuration center with etcd support and improved discovery stability

This release introduces a new configuration center (\core/configcenter\) that allows applications to subscribe to and automatically reload structured configuration (JSON, YAML, TOML) from etcd, complete with listener callbacks for change notifications. The underlying discovery mechanism in \core/discov\ has been refactored to support etcd authentication and TLS via new \EtcdConf\ fields and \WithPubEtcdAccount\/\WithSubEtcdTLS\ options. Additionally, the etcd publisher now watches for key deletions to automatically re-register, and the subscriber container prevents memory leaks by handling duplicate PUT events and cleaning up stale key mappings.

core/discov · high confidence

New error utilities and improved concurrency safety in core/errorx

The errorx package introduces new helper functions for error handling: \Chain\ executes a series of functions and returns the first error encountered, \In\ checks if an error matches any in a provided list using \errors.Is\, and \Wrap\/\Wrapf\ create wrapped errors with custom messages while preserving the underlying error for unwrapping. Additionally, \AtomicError\ has been optimized to use \sync/atomic\ instead of a mutex for better performance, and \BatchError\ now uses \errors.Join\ to combine multiple errors into a single error that supports \errors.Is\ checks, while ensuring thread-safety for concurrent additions.

core/errorx · high confidence

New goctl template management commands

The goctl CLI now includes a dedicated template management subsystem with init, clean, update, and revert commands. Users can initialize default templates, remove all custom templates, update specific template categories (such as API, RPC, Docker, Kube, Mongo, and Gateway) to their latest versions, or revert individual template files to their original state, providing better control over the code generation templates.

tools/goctl/tpl · high confidence

New goctl update service for binary distribution

A new HTTP service has been added to the goctl tooling to facilitate binary updates. This service serves the goctl binary from a specified directory and implements an MD5 checksum validation mechanism: it compares the local file's hash against the Content-MD5 header in incoming requests, returning a 304 Not Modified response if they match, or serving the file with the current checksum header if they differ. The service is configured via a JSON file and listens on a specified address.

tools/goctl/update · high confidence

New goctl utility library for code generation helpers

The \tools/goctl/util\ package introduces core utilities for the goctl code generator, including Git repository cloning (\git.go\), standardized code headers with versioning (\head.go\), string manipulation and Go keyword escaping (\string.go\), and a template execution engine with optional Go formatting (\templatex.go\). These components provide the foundational logic for generating, formatting, and managing source code files within the goctl ecosystem.

tools/goctl/util · high confidence

New internal gateway components for request parsing, descriptor handling, and header processing

The gateway now includes a new internal package (\gateway/internal\) that provides the core building blocks for HTTP-to-gRPC translation. This adds a descriptor source to map gRPC methods to HTTP paths (supporting \google.api.http\ annotations), a request parser that unmarshals JSON bodies while ignoring unknown fields, an event handler to map gRPC metadata to HTTP headers, and a header processor that forwards OpenTelemetry trace context headers (\traceparent\, \tracestate\, \baggage\) and custom metadata. These components enable the gateway to correctly route HTTP requests to gRPC services, propagate distributed tracing information, and handle request payloads robustly.

gateway/internal · high confidence

New internal health check subsystem with composite probe support

The internal/health package introduces a new health management system that allows registering multiple component probes to determine overall service readiness. It provides a global comboHealthManager that aggregates individual probes, exposing methods to mark components as ready or not ready and check their status. A new HTTP handler is created to expose this status, returning a 200 OK when all probes are ready and a 503 Service Unavailable with verbose details of which components are not ready otherwise. This enables external systems to monitor the application's health based on the combined state of its internal components.

internal/health · high confidence

New internal middleware for serving static files from embedded file systems

The \rest/internal/fileserver\ package now provides a \Middleware\ function that allows the REST layer to serve static assets using Go's \embed.FS\. This middleware handles path normalization, supports root paths, and correctly manages \index.html\ redirects, enabling static content to be served directly from compiled binaries without relying on external file system directories.

rest/internal/fileserver · high confidence

New internal response writer helpers for header and status code management

Added two new internal HTTP response writer wrappers in the rest/internal/response package: HeaderOnceResponseWriter, which ensures only the first call to WriteHeader takes effect, and WithCodeResponseWriter, which delays sealing the response and exposes the status code via a Code field while supporting Unwrap for compatibility with http.ResponseController. Both wrappers implement standard http.ResponseWriter interfaces including Flush and Hijack, and include corresponding unit tests to verify their behavior.

rest/internal/response · high confidence

New logc package provides context-aware logging

A new \core/logc\ package has been introduced to provide context-aware logging capabilities. This package exposes a comprehensive set of logging functions—including \Debug\, \Info\, \Error\, and \Slow\ variants (standard, formatted, value, and writer)—that accept a \context.Context\ to associate log entries with specific request scopes. It also supports global field injection via \AddGlobalFields\ and lazy evaluation of log messages through \\*fn\ functions (e.g., \Debugfn\, \Errorfn\). The package acts as a wrapper around the existing \logx\ library, reusing its configuration and setup mechanisms (\SetUp\, \MustSetup\, \SetLevel\) while ensuring correct caller information is captured via context-aware logger retrieval.

core/logc · high confidence

New logtest package for simplified logging assertions in tests

A new \core/logx/logtest\ package has been introduced to streamline testing of logging behavior. It provides utilities such as \NewCollector\ to capture log output into a buffer for inspection, \Discard\ to suppress logs, and \PanicOnFatal\ to prevent test processes from exiting on fatal log entries. The package includes helper methods like \Content()\ and \Reset()\ on the collector buffer, along with corresponding unit tests to verify its functionality.

core/logx/logtest · high confidence

New pathvar package for accessing path variables in user-defined routers

A new \rest/pathvar\ package has been introduced, providing \Vars\ and \WithVars\ functions to read and write HTTP request path variables via context. This allows users of user-defined routers to easily access path parameters that were previously difficult to retrieve outside of the framework's standard handler chain.

rest/pathvar · high confidence

New range clamping functions and updated entropy calculation in mathx

The core/mathx package now includes new generic utility functions AtLeast, AtMost, and Between in range.go to clamp numeric values within a specified range. Additionally, the CalcEntropy function in entropy.go has been updated to accept a map\[any\]int instead of map\[interface{}\]int, automatically calculates the total count from the map values, and applies an epsilon floor to probability calculations to prevent log(0) errors. The deprecated MaxInt and MinInt functions in int.go now delegate to the built-in max and min functions.

core/mathx · high confidence

New string case conversion utilities in goctl

The goctl tool now includes a new stringx utility package that provides methods for converting strings between different cases, including Title, Camel, and Snake case, as well as utilities for checking whitespace and empty strings.

tools/goctl/util/stringx · high confidence

New zipx utility for safe zip extraction with permission preservation

A new \zipx\ package has been added to \tools/goctl/util/zipx\ to provide a safe method for unpacking zip archives. This utility prevents Zip Slip vulnerabilities by validating file paths and rejecting those containing directory traversal sequences (e.g., \..\). It also ensures that executable permissions are preserved on extracted files, maintaining the original file modes for regular files. The package includes a test suite verifying correct file extraction, permission handling, and error cases for invalid inputs.

tools/goctl/util/zipx · high confidence

Prometheus metrics now support summary vectors, gauge decrement/subtraction, histogram float observations, and constant labels

Users can now track distribution quantiles via a new SummaryVec type, and GaugeVecs support Dec() and Sub() operations in addition to existing methods. HistogramVecs now accept ConstLabels for static metric attributes and expose an ObserveFloat() method for float64 observations. All metric operations (Counter, Gauge, Histogram, Summary) are now wrapped in an update() function that checks prometheus.Enabled(), ensuring metrics are only recorded when the Prometheus agent is active.

core/metric · high confidence

Repository governance and documentation overhaul

The repository has been restructured to improve community governance and onboarding. New standard policy files have been added: a CONTRIBUTING.md guide for new contributors, a SECURITY.md policy defining supported versions (\>= 1.4.4) and vulnerability reporting, and a Code of Conduct based on the Contributor Covenant v2.1. The project license is now explicitly MIT (LICENSE). Documentation has been expanded with localized READMEs for Chinese (readme-cn.md) and Korean (readme-ko.md), and the English README now includes an 'AI-Native Development' section detailing workflows for AI assistants like Claude Code and Cursor, including optional MCP integration via mcp-zero. Additionally, legacy CI and linting configurations (.gitlab-ci.yml, .golangci.yml, sonar-project.properties) have been removed, and .gitignore/.dockerignore have been updated to reflect the new structure.

(repo-wide) · high confidence

Runtime stats monitoring and profiling refactoring

The profiling subsystem now includes a new runtime statistics monitor that periodically prints goroutine, memory, and GC stats to stdout (or a custom writer) at a configurable interval, defaulting to every 5 seconds. The internal profiling implementation has been refactored: the \ProfileCenter\ and related structs are renamed to lowercase (internal), the \tablewriter\ dependency is removed in favor of direct CSV-style string building for reports, and the module import path is updated from \zero\ to \github.com/zeromicro/go-zero\. Tests have been added to verify the new runtime stats output and the profiling report generation.

core/prof · high confidence

SQL client metrics, read/write routing, and ORM improvements

The sqlx package now exposes Prometheus metrics for SQL client requests (duration, errors, slow queries) and connection pool statistics (open, in-use, idle, wait counts) under the 'sql\_client' namespace. It introduces context-based read/write routing strategies, allowing users to explicitly target primary or replica databases via WithReadPrimary, WithReadReplica, and WithWrite context helpers. The ORM layer has been updated to support the 'any' type alias, handle pointer-to-pointer scanning, and respect struct field tags with a '-' value to skip fields. Additionally, the BulkInserter now uses a read-write lock for thread-safe statement updates, and error handling has been modernized to use errors.As and errors.Is for better compatibility with Go's error wrapping.

core/stores/sqlx · high confidence

Stream processing, parallel execution, and retry control enhancements

The core/fx package introduces a new Stream API (stream.go) for functional-style data processing, including operations like Filter, Map, Group, and Distinct, alongside a new ParallelErr function that executes functions concurrently and aggregates errors. The retry mechanism has been significantly expanded with DoWithRetryCtx for context-aware retries, plus new options to configure timeouts, intervals, and error ignoring. Additionally, DoWithTimeout now captures and includes full stack traces on panics to improve debugging.

core/fx · high confidence

Support for ignoring struct fields via db tag and PostgreSQL mode in field name extraction

The \RawFieldNames\ function in the core builder now respects the \db:"-"\ struct tag to exclude specific fields from database queries, including cases where the tag includes options (e.g., \db:"-,type=varchar"\). It also supports a PostgreSQL mode that outputs unquoted field names instead of backtick-quoted identifiers. Additionally, a new \PostgreSqlJoin\ helper is provided to format field assignments for PostgreSQL update statements.

core/stores/builder · high confidence

goctl API generator scaffolds complete Go service projects with SSE and test support

The \goctl\ API code generator in \tools/goctl/api/gogen\ now produces a full Go project structure from an \.api\ specification, including configuration, main entry point, service context, types, handlers, logic, and route registration files. It supports Server-Sent Events (SSE) by generating specialized handler and logic templates when the \sse: true\ annotation is present, and can optionally generate unit and integration test scaffolding via the \--test\ flag. Generated files are clearly marked as either 'Safe to edit' (scaffolded code) or 'DO NOT EDIT' (regenerated code like routes and types), and include the goctl version in their headers.

tools/goctl/api/gogen · high confidence

goctl now supports Go workspaces and custom module initialization

The goctl code-generation tool now detects and respects Go workspaces (go.work), automatically adding the current directory to the workspace when necessary. It also introduces a new module context system that can initialize a go.mod file with a custom module name if one does not already exist, and correctly resolves project paths in both Go module and legacy GOPATH modes.

tools/goctl/util/ctx · high confidence

goctl now wraps errors with version and environment context

The goctl tool now provides a new error wrapping mechanism that enriches standard errors with the current goctl version and environment details. When an error is wrapped using the new \Wrap\ function, the resulting error message includes the original error, the output of \goctl env\, and any additional custom messages provided, making debugging easier by giving users immediate context about the tool's state at the time of failure.

tools/goctl/internal/errorx · high confidence

goctl rpc generator now supports external proto imports and custom Go module names

The \goctl rpc\ code generator has been updated to resolve and include transitively imported \.proto\ files when invoking \protoc\, allowing services to depend on external proto definitions. Additionally, the generator now accepts a custom Go module name via the \--module\ flag (exposed as \ZRpcContext.Module\), enabling the generated \go.mod\ and import paths to match a specific module layout rather than defaulting to the directory name.

tools/goctl/rpc/generator · high confidence

goctl rpc now supports external proto imports and cross-package types

The \goctl rpc\ code generator now supports importing \.proto\ files from external directories via the \-I\ / \--proto\_path\ flag, including full transitive dependency resolution. It also automatically resolves cross-package type references (where imported protos have different \go\_package\ values) and allows Google protobuf well-known types (such as \google.protobuf.Empty\ and \Timestamp\) to be used directly as RPC request/response parameters. Previously, all types had to be defined in the same proto file, and dotted type names were rejected.

tools/goctl/rpc · high confidence

goctl standalone CLI tool and build infrastructure

The \tools/goctl\ directory now contains the complete source code and build infrastructure for the standalone \goctl\ CLI tool (version 1.8.4-beta). This includes the main entry point (\goctl.go\), which disables default logging and load balancing to function as a standalone utility, and a new Dockerfile that builds a multi-stage image using \golang:alpine\ and installs \protoc-gen-go\ and \protoc-gen-go-grpc\ as dependencies. Build automation is provided via a \Makefile\ and \build.sh\ script, enabling cross-compilation for Linux, macOS, and Windows (amd64/arm64) and packaging the binaries into zips. The release notes in \change.md\ highlight new features for this version, including support for operation IDs in Swagger generation, the ability to use definitions in API specs, and a \--type-group\ flag to separate types into individual files during code generation. Additionally, a new \naming\ utility package has been added to standardize filename formatting (camel, snake, lower case).

tools/goctl · high confidence

Removals

Removal of Beanstalk-based distributed queue implementation

The distributed queue package (dq) has been removed, eliminating the ability to use Beanstalkd as a message broker for task production and consumption. This change deletes the core components including the producer and consumer clusters, connection management, and configuration structures that previously handled job scheduling, delayed execution, and distributed task processing via Beanstalk tubes and Redis for coordination.

dq · high confidence

Removal of ClickHouse store implementation

The ClickHouse database store implementation has been removed from the core stores module. The file \core/stores/clickhouse/clickhouse.go\, which previously provided a \New\ function to initialize a ClickHouse connection using the \github.com/kshvakov/clickhouse\ driver, is no longer present. Users relying on this specific integration will need to migrate to an alternative solution or external contribution.

core/stores/clickhouse · high confidence

Removal of Kafka message queue implementation

The Kafka-based message queue functionality has been removed from the kq package. This change deletes the configuration structures, the producer (pusher) logic for sending messages, and the consumer (queue) logic for processing messages, effectively eliminating the ability to interact with Kafka brokers through this component.

kq · high confidence

Removal of Stash log ingestion and filtering service

The Stash component, which ingested logs from Kafka and wrote them to Elasticsearch, has been removed. This change deletes the core application entry point, the configuration structures, the Kafka message handler, the filter logic (including drop and field-removal rules), and the Elasticsearch indexing and writing clients. Users will no longer have access to this specific log aggregation and filtering pipeline.

stash · high confidence

Removal of core HTTP, RPC, and queue infrastructure

This change removes the entire core HTTP handler, router, and server implementation, including logging, tracing, and timeout middleware, as well as the core gRPC client and server infrastructure with its interceptors and discovery integration. Additionally, the core Redis queue producer and pusher implementations are deleted. These removals eliminate the framework's built-in support for HTTP request handling, gRPC service communication, and Redis-based message queuing.

(repo-wide) · high confidence

Removal of deprecated mgo MongoDB driver support

The \core/stores/mongo\ package has been removed, eliminating support for the legacy \github.com/globalsign/mgo\ driver. This change deletes the entire MongoDB storage implementation, including the \Model\, \Collection\, \Query\, \Pipe\, and \Iter\ abstractions, along with their associated tests and mock files. Users relying on this MongoDB store will need to migrate to an alternative database driver or implementation.

core/stores/mongo · high confidence

Removal of legacy example code and infrastructure

This change removes a large set of example files and associated infrastructure configurations from the repository. The deleted content includes demonstration code for various subsystems such as Beanstalk, Bloom filters, circuit breakers, ClickHouse, and file processing, as well as complete deployment examples for etcd-based service discovery and graceful API/RPC services. Corresponding Kubernetes manifests, Dockerfiles, and Makefiles used to build and deploy these examples have also been removed, indicating a cleanup of outdated or unused demonstration material.

example · high confidence

Removal of legacy mgo-based cached MongoDB store

The \core/stores/mongoc\ package, which provided a cached MongoDB collection and model layer built on the deprecated \github.com/globalsign/mgo\ driver, has been removed. This eliminates the legacy caching implementation and its associated tests, requiring users to migrate to the current MongoDB store implementation.

core/stores/mongoc · high confidence

Removal of rpcx authentication and client infrastructure

The rpcx package's authentication and client management capabilities have been removed. The \auth\ package (including \Authenticator\, \Credential\, and \ParseCredential\) is deleted, along with the \interceptors\ package that provided \StreamAuthorizeInterceptor\ and \UnaryAuthorizeInterceptor\. The \client.go\ file, which handled \RpcClient\ creation with credential injection and timeout options, is removed, as is \proxy.go\ which managed backend connections using parsed credentials. Configuration structures \RpcServerConf\ and \RpcClientConf\ in \config.go\ are also deleted, effectively stripping the rpcx module of its built-in auth, client, and proxy logic.

rpcx · high confidence

Removal of the ngin HTTP engine and configuration

The ngin HTTP engine, including its configuration structures (NgConf, SignatureConf), the main engine implementation (ngin.go), server logic (server.go), and type definitions (types.go), has been completely removed from the codebase. This deletion eliminates the ability to configure and run the HTTP server with features such as JWT authentication, request signature verification, middleware chaining, and adaptive load shedding via the previous ngin package.

ngin · high confidence

Removal of the rq Redis-based message queue package

The entire \rq\ package has been removed from the codebase, eliminating the Redis-backed message queue functionality. This deletion includes the core queue and pusher implementations (\queue.go\, \pusher.go\), configuration structures (\config.go\), and supporting utilities for server change tracking and incremental updates (\update/\ directory). Users relying on this package for message queuing capabilities will no longer have access to these components.

rq · high confidence

Security

Security hardening in core/codec: RSA OAEP support, ECB deprecation, and Gzip decompression limits

This change introduces several security improvements and behavioral updates in the codec package. RSA encryption now supports OAEP with SHA-256 via new \NewRsaOAEPEncrypter\ and \NewRsaOAEPDecrypter\ functions, while the legacy PKCS\#1 v1.5 methods are marked deprecated due to padding oracle vulnerabilities. AES-ECB mode functions are also deprecated in favor of AES-GCM. Additionally, \Gunzip\ now limits decompressed output to 100MB to prevent zip-bomb attacks, and Diffie-Hellman key validation was tightened to strictly reject public keys outside the valid range (0 \< key \< p).

core/codec · high confidence

Behavioural changes

Add FreeBSD support and update Go build constraints

The file system utilities now support FreeBSD in addition to Linux and Darwin, allowing the CloseOnExec functionality to work on this platform. The code also updates deprecated Go build constraints from the old // +build syntax to the newer //go:build syntax for better compatibility with recent Go versions.

core/fs · high confidence

Bloom filter now supports context-aware operations and externalized Lua scripts

The bloom filter implementation in core/bloom has been updated to support context cancellation via new AddCtx and ExistsCtx methods, allowing callers to control timeouts and cancellation for Redis operations. Internally, the module now uses the ScriptRun API instead of the legacy Eval method for executing Redis scripts, and the Lua scripts for setting and testing bits have been moved from inline strings to external files (setscript.lua and testscript.lua) embedded at compile time. Additionally, the package import path has been updated from zero to github.com/zeromicro/go-zero, and the test suite has been refactored to use the centralized redistest helper instead of miniredis.

core/bloom · high confidence

Cache API refactored with context support and Go 1.18 types

The cache package in core/stores/cache has been refactored to expose a modernized API. All cache operations (Get, Set, Del, Take) now have Ctx variants accepting a context.Context, and the generic interface uses the Go 1.18 'any' type instead of 'interface{}'. The internal implementation was moved from core/stores/internal to core/stores/cache, and the concurrency barrier was switched from SharedCalls to SingleFlight. Additionally, the cache statistics type was renamed from CacheStat to Stat, and the cleaner's timing wheel was made thread-safe using atomic.Value.

core/stores/cache · high confidence

Centralized HTTP header constants in internal package

The rest/internal/header package now provides a centralized set of constants for common HTTP headers and content types, including ApplicationJson, CacheControl, Connection, ContentType, and ContentTypeEventStream. This change consolidates header definitions to ensure consistency across the REST layer.

rest/internal/header · high confidence

Circuit breaker now supports context cancellation

The circuit breaker in core/breaker now exposes context-aware methods (AllowCtx, DoCtx, DoWithAcceptableCtx, DoWithFallbackCtx, DoWithFallbackAcceptableCtx) that respect context deadlines and cancellation. If the provided context is done, the breaker returns the context error (e.g., context.DeadlineExceeded or context.Canceled) instead of proceeding with the request. Additionally, the module has been renamed from zero to github.com/zeromicro/go-zero, and the internal tracking has been refactored to use a typed bucket with success/failure/drop counts, replacing the previous state-based open/closed model with a more granular history-based approach.

core/breaker · high confidence

Collection types migrate to Go generics and modernize APIs

The core/collection package has been refactored to use Go generics, replacing \interface{}\ with \any\ across Cache, SafeMap, Ring, and Queue. The legacy untyped Set is replaced by a new generic \Set\[T comparable\]\ with a simplified API (e.g., \Add\, \Contains\, \Keys\, \Clear\). Cache now supports per-key expiration via \SetWithExpire\ and improves \Take\ with a double-check pattern to avoid redundant fetches. Queue growth is optimized with a hybrid doubling/1.25x strategy, and Ring gains thread safety via \sync.RWMutex\ with overflow protection. RollingWindow is now generic (\RollingWindow\[T, B\]\) with configurable bucket types and aligned time boundaries. TimingWheel methods now return errors (e.g., \ErrClosed\, \ErrArgument\) and support resetting timers after drain.

core/collection · high confidence

Consistent hash API modernization and Md5Hex performance improvement

The consistent hash implementation in core/hash now uses Go's \any\ type instead of \interface{}\ for node parameters and return values, and has updated its internal import path to \github.com/zeromicro/go-zero/core/lang\ for representation logic. Additionally, the \Md5Hex\ function has been optimized to use \encoding/hex\ directly, providing better performance than the previous \fmt.Sprintf\ approach. These changes also include minor test refinements to ensure deterministic behavior and correct transfer ratio calculations.

core/hash · high confidence

Content security logic moved to rest/internal/security with logging and signature verification updates

The content security implementation has been relocated from core/httphandler/internal to rest/internal/security, updating package references to the zeromicro/go-zero module. The signature verification logic in VerifySignature has been adjusted to always return the invalid token code when signatures mismatch, while logging the discrepancy via logc instead of logx. Additionally, exported error variables and key methods now include documentation comments, and comprehensive unit tests have been added to cover encrypted, unencrypted, and invalid header scenarios.

rest/internal/security · high confidence

Context support and module rename in SQL cache layer

The sqlc package now supports context propagation for all cache-aware database operations (Exec, QueryRow, QueryRowIndex, etc.) via new \*Ctx variants, allowing callers to control timeouts and cancellation. The module has been renamed from 'zero' to 'zeromicro', updating all import paths. Additionally, the internal caching mechanism switched from SharedCalls to SingleFlight for better concurrency handling, and the codebase migrated from interface{} to any.

core/stores/sqlc · high confidence

Define core project and OS constants in goctl

The goctl tool now centralizes its core identity and supported operating system constants in a new settings file. Users can rely on the project name being identified as 'zero' and the official repository URL as 'github.com/zeromicro/go-zero'. Additionally, explicit constants for Windows, macOS, Linux, JavaScript, and iOS environments are now available for internal use within the code generation tool.

tools/goctl/vars · high confidence

Deprecation of SQL builder helper functions in goctl

The \tools/goctl/model/sql/builderx\ package has been deprecated in favor of the corresponding functions in \github.com/zeromicro/go-zero/core/stores/builder\. Specifically, \FieldNames\, \RawFieldNames\, and \PostgreSqlJoin\ are now thin wrappers that delegate to the core library, signaling that users should migrate their code to use the central builder package directly to avoid relying on this legacy location.

tools/goctl/model/sql/builderx · high confidence

Enhanced HTTP request parsing and validation in rest/httpx

The \rest/httpx\ package now supports parsing form arrays in three notations (standard repeated keys, comma-separated, and bracket notation) and allows configuring a custom validator via \SetValidator\ to run after parsing. The \Parse\ function has been updated to handle \Unmarshaler\ interfaces, parse request headers, and apply validation, while \GetFormValues\ now enforces a 2048 parameter limit to prevent excessive memory usage.

rest/httpx · high confidence

Enhanced process lifecycle management and cross-platform signal handling

The core/proc package now supports FreeBSD in addition to Linux and Darwin, with build tags updated across goroutines, profile, shutdown, and signals modules. Shutdown behavior has been refactored to allow configurable wait and wrap-up times via a new ShutdownConf struct and Setup function, replacing the previous fixed delays. Signal handling now explicitly supports SIGINT (Ctrl+C) alongside SIGTERM, ensuring the process Done channel is closed consistently. Profiling via SIGUSR2 is now automatically stopped after one minute. Additionally, the shutdown listener notification mechanism has been improved to run listeners concurrently using a RoutineGroup and ensures cleanup, while Windows polyfills now return listener functions directly to allow callers to manage execution.

core/proc · high confidence

Executor API modernization and race-condition fixes

The executors package (Bulk, Chunk, Periodical, and Delay) now uses the Go 1.18+ \any\ type alias instead of \interface{}\ for task handling, and imports have been updated to the \github.com/zeromicro/go-zero\ module path. The PeriodicalExecutor's internal logic has been refactored to resolve data races and potential deadlocks: it now uses atomic counters and a barrier for safe WaitGroup management, ensures the background flush goroutine completes pending tasks before exiting, and adds tests to verify correct behavior during panics and high-concurrency scenarios.

core/executors · high confidence

Expanded SQL data type mapping and conversion logic

The SQL model converter now supports a broader range of database column types, including explicit handling for PostgreSQL-specific types like \bpchar\ and array types (e.g., \\_int2\, \\_varchar\) which map to \pq\ package arrays. The conversion logic has been updated to consistently map integer types to \int64\ and floating-point types to \float64\ in Go, while also supporting unsigned variants (e.g., \uint64\) and nullable wrappers (e.g., \sql.NullInt64\). This ensures more accurate Go type generation for diverse SQL schemas.

tools/goctl/model/sql/converter · high confidence

Graceful fallback for missing hostname

The sysx package no longer terminates the application if the operating system fails to provide a hostname. Instead, it now assigns a random ID as the hostname, ensuring the service continues to run without crashing during initialization.

core/sysx · high confidence

Improved adaptive load shedding with recovery logic and configurable logging

The adaptive load shedder in core/load now uses a more robust algorithm to determine when to drop requests, introducing an overload factor to prevent premature shedding and adding a cool-off period to ensure the service recovers from overload states before accepting traffic again. The internal tracking of request windows has been updated to use generic types for better type safety, and the module import paths have been updated to github.com/zeromicro/go-zero. Additionally, users can now disable shedding statistics logs via the new DisableLog function, providing finer control over observability output.

core/load · high confidence

Improved reliability and test coverage for file line reading

The \FirstLine\ and \LastLine\ functions in \core/filex\ have been refactored to correctly handle edge cases, such as empty files and files without trailing newlines, ensuring they return empty strings instead of errors. The underlying logic for \LastLine\ was optimized to use dynamic buffer sizing based on the remaining file offset, improving efficiency for large files. Additionally, comprehensive tests were added to verify these behaviors, including scenarios for files exactly matching the buffer size and large multi-chunk files.

core/filex · high confidence

Introduce configurable middleware chaining in REST handlers

Users can now build and customize HTTP middleware pipelines for REST endpoints using the new \rest/chain\ package. This change adds a \Chain\ interface with \Append\ and \Prepend\ methods, allowing developers to explicitly define the order in which middlewares are applied to handlers, replacing the previous implicit or built-in middleware behavior.

rest/chain · high confidence

JSON marshaling now preserves HTML characters and adds string output support

The \core/jsonx\ package now uses \json.Encoder\ with HTML escaping disabled, ensuring that special characters like \&\, \\<\, and \\>\ are preserved in API responses rather than being converted to Unicode escape sequences. Additionally, a new \MarshalToString\ function has been added to allow direct serialization to a string, and the internal error formatting has been updated to use error wrapping for better debugging.

core/jsonx · high confidence

KV store interface expanded with context support and new Redis commands

The KV store interface now exposes context-aware variants (Ctx suffix) for nearly all operations, allowing callers to pass cancellation or timeout contexts. New commands have been added including GetSet, Lindex, ZaddFloat, and Zrevrank, while generic interface types have been updated from interface{} to any. The module import path has been updated from zero to github.com/zeromicro/go-zero, and the internal configuration type KvConf is now an alias for cache.ClusterConf.

core/stores/kv · high confidence

Kubernetes resolver now uses EndpointSlice API

The zRPC Kubernetes resolver has been updated to watch and resolve service endpoints using the newer EndpointSlice API (k8s.io/api/discovery/v1) instead of the legacy Endpoints API. This change improves the accuracy and performance of service discovery in Kubernetes clusters by leveraging the more scalable EndpointSlice resource, ensuring that RPC clients resolve to the correct, up-to-date pod addresses as defined by modern Kubernetes service mesh configurations.

zrpc/resolver/internal/kube · high confidence

MCP server migrates to official go-sdk with dual transport support and request metadata bridge

The MCP package has been rewritten to use the official Model Context Protocol Go SDK (v1.2.0), replacing the previous custom implementation. This migration introduces type-safe tool registration using Go generics, which automatically generates JSON schemas from struct tags, and supports both SSE (2024-11-05 spec) and Streamable HTTP (2025-03-26 spec) transports via a new \UseStreamable\ configuration option. The public API has changed: \server.AddTool\ is no longer available; instead, users must call \mcp.AddTool(server, tool, handler)\ which delegates to the SDK. Additionally, an opt-in request metadata bridge allows handlers to access HTTP headers, query parameters, and path variables via context helpers like \HeaderFromContext\ and \QueryFromContext\.

mcp · high confidence

MapReduce concurrency tool refactored with generics, context support, and panic handling

The \core/mr\ package introduces a generic version of the MapReduce concurrency tool, replacing previous \interface{}\-based signatures with Go generics (e.g., \MapReduce\[T, U, V\]\). This update adds explicit context support via \WithContext\ to allow cancellation of map/reduce operations, and improves reliability by handling panics in the calling goroutine and mapper functions more robustly, including better stacktrace information. The module has been renamed from \tal-tech\ to \zeromicro\, and the package path is now \core/mr\. Fuzz tests have been added to verify stability under random inputs and panic scenarios.

core/mr · high confidence

Mapping engine refactored with TOML support and enhanced validation

The core mapping engine has been significantly refactored to support TOML configuration files via new \UnmarshalTomlBytes\ and \UnmarshalTomlReader\ functions, which convert TOML to JSON before processing. The unmarshaler now accepts \UnmarshalOption\ functions to customize behavior, such as \WithCanonicalKeyFunc\ for case-insensitive key matching, and introduces a new \inherit\ tag option to allow fields to inherit values from parent config nodes. Validation logic has been strengthened to strictly enforce \options\ and \range\ constraints during unmarshaling, and the \Marshal\ function now supports serializing anonymous (embedded) struct fields. Additionally, the codebase has been modernized by replacing \interface{}\ with \any\ and updating internal package imports to the \github.com/zeromicro/go-zero\ module path.

core/mapping · high confidence

Migrate JWT library and update token parsing logic

The token parsing functionality has moved from the core httpsecurity package to the rest/token package. The underlying JWT library was upgraded from dgrijalva/jwt-go to golang-jwt/jwt/v4, requiring updates to the parser initialization and type definitions (using any instead of interface{}). Additionally, the token parsing behavior was adjusted to ensure the claim history count is incremented even when a previous secret is used for validation, and test requests now explicitly use http.NoBody.

rest/token · high confidence

Migration guidance for goctl 1.3.4 model module changes

When upgrading to goctl 1.3.4 or later, users will now see a helpful message if their project still contains the old single-file model structure (e.g., \XXXmodel.go\) without the new generated counterpart (\XXXmodel\_gen.go\). This new migration note system, located in the \migrationnotes\ package, detects the presence of legacy model files and guides users to back up their original file, re-run the generation command to create the new split files, and then manually populate the new \XXXmodel.go\ with custom code as indicated by comments in the generated \\_gen.go\ file.

tools/goctl/model/sql/command/migrationnotes · high confidence

MongoDB cache model updated to use official Go driver v2

The cached MongoDB model in core/stores/monc now uses the official MongoDB Go driver v2 (go.mongodb.org/mongo-driver/v2) instead of the legacy mgo driver. This change updates the underlying database connectivity and aligns with the v2 API, requiring users to migrate their imports and configuration to the new driver version as outlined in the included migration guide.

core/stores/monc · high confidence

MongoDB model generation updated to use mon/monc stores and MongoDB Go driver v2

The goctl MongoDB model templates have been rewritten to support the new \mon\ and \monc\ storage packages (replacing previous implementations) and the MongoDB Go driver v2. Generated models now utilize these updated libraries for database operations, and the code generation logic has been refactored to use Go embeds for template management. This change affects the structure and dependencies of generated MongoDB model code, including error definitions and custom model interfaces.

tools/goctl/model/mongo/template · high confidence

MongoDB store refactored to use official Go driver v2 with new bulk insertion and client management

The MongoDB storage layer has been rewritten to use the official go.mongodb.org/mongo-driver/v2, replacing the legacy mgo driver. This update introduces a new \BulkInserter\ for efficient batch document insertion, a dedicated \ClientManager\ to handle MongoDB client lifecycle and connection pooling, and a \Model\ struct that wraps collection operations with circuit breaking and distributed tracing. The change also adds configuration options for custom type codecs, logging control, and timeouts, along with comprehensive tests for the new components.

core/stores/mon · high confidence

New AST-based API parser and formatter for goctl

The goctl API tooling now uses a new parser located in \tools/goctl/pkg/parser/api\ that builds an Abstract Syntax Tree (AST) from \.api\ files, replacing the previous implementation. This change introduces a new formatting engine (\tools/goctl/pkg/parser/api/format\) that can reformat API source code while preserving comments and structure, and an analyzer (\tools/goctl/pkg/parser/api/parser/analyzer\) that converts the AST into the internal \spec.ApiSpec\ representation. The new parser enforces stricter type rules, such as disabling nested structs in array and map types, and supports new syntax features like special characters in route paths and hyphen-only prefixes. Comprehensive tests are included to verify the formatting and parsing logic.

tools/goctl/pkg/parser · high confidence

PostgreSQL store switches to pgx driver and simplifies API

The PostgreSQL store now uses the pgx driver (github.com/jackc/pgx/v5/stdlib) instead of lib/pq, changing the internal driver name to 'pgx'. The public API is simplified: the function is now New instead of NewPostgre, and it returns a sqlx.SqlConn. A basic test verifies that New returns a non-nil connection.

core/stores/postgres · high confidence

Prometheus metrics can now be enabled programmatically

The Prometheus integration now supports dynamic activation via new \Enable()\ and \Enabled()\ functions, allowing services to start metrics collection on demand rather than relying solely on configuration presence. The \StartAgent\ function has been updated to set the internal enabled flag when invoked, ensuring the global state reflects active usage. Additionally, the module has been renamed from \tal-tech\ to \zeromicro\, and import paths have been updated to reflect this change.

core/prometheus · high confidence

Queue API simplification and Go 1.18+ compatibility

The core/queue package has been refactored to simplify its public API and align with modern Go standards. The generic \QueuePusher\ interface has been renamed to \Pusher\, and specific implementations like \BalancedQueuePusher\ and \MultiQueuePusher\ have been renamed to \BalancedPusher\ and \MultiPusher\ respectively, with their constructors updated accordingly. Additionally, the codebase has migrated from \interface{}\ to the \any\ type alias for better readability and compatibility with Go 1.18+, and import paths have been updated from the legacy \zero/...\ prefix to \github.com/zeromicro/go-zero/...\.

core/queue · high confidence

REST server refactored to support configurable middleware chains and serverless deployment

The REST server implementation has been restructured to allow users to disable specific built-in middlewares (such as tracing, logging, and metrics) via the RestConf configuration, and to replace the default middleware chain entirely using the new WithChain option. Additionally, a new Serverless wrapper type has been introduced to facilitate running the REST server in serverless environments, and CORS handling has been expanded with new options to customize headers and responses.

rest · high confidence

Rate limiters now support context cancellation and external Lua scripts

The period and token limiters in core/limit have been updated to support context-aware operations, allowing requests to be cancelled via context deadlines or cancellation signals. New methods like TakeCtx and AllowCtx were added to PeriodLimit and TokenLimiter respectively, replacing the previous Eval-based execution with ScriptRunCtx. Additionally, Lua scripts for rate limiting logic have been extracted from Go source code into separate files (periodscript.lua and tokenscript.lua) and embedded at compile time, improving maintainability and compatibility with certain Redis providers like Aliyun. The module path has also been updated from zero to github.com/zeromicro/go-zero.

core/limit · high confidence

Redis client refactored with go-redis v9, hooks, and metrics

The Redis store has been upgraded to use go-redis v9, introducing a new hook-based architecture that integrates circuit breaking, performance duration tracking, and Prometheus metrics collection for all Redis operations. Configuration now supports username, TLS, protocol version negotiation, and identity disabling to improve compatibility with various Redis server versions. Blocking operations are isolated into dedicated nodes to prevent connection pool exhaustion, and Lua scripts for distributed locking are now embedded from external files for better maintainability.

core/stores/redis · high confidence

Refactored CPU statistics collection to support cgroups v2 and improve reliability

The CPU statistics subsystem in core/stat/internal has been refactored to support both cgroups v1 and v2, ensuring accurate CPU usage reporting on modern Linux systems. The implementation now initializes CPU stats lazily only when needed, rather than at startup, and gracefully handles environments without cgroup support (such as WSL or systems without /proc/stat) by returning zero usage instead of panicking. Additionally, CPU usage calculations are now capped at 100% to prevent overflow, and the module path has been updated to reflect the zeromicro organization.

core/stat/internal · high confidence

Refactored REST handlers with improved logging, timeout, and security behaviors

The REST handler middleware layer has been refactored to improve logging context, timeout handling, and security defaults. Log handlers now use context-aware logging and support configurable slow thresholds for both standard and Server-Sent Events (SSE) requests. The timeout handler now correctly ignores timeouts for WebSocket and SSE connections and logs client-closed requests as HTTP 499. Security handlers now return HTTP 401 Forbidden instead of Unauthorized for strict signature verification failures, and the authentication handler has been updated to use the golang-jwt/v4 library with improved error handling and callback ordering.

rest/handler · high confidence

Refactored REST server startup and logging context handling

The REST server startup logic has been consolidated into a new internal starter that manages HTTP/HTTPS listening and integrates with the health check system for graceful shutdown. Additionally, the logging subsystem was moved to the internal package and refactored to use a private context key for the log collector, replacing the previous public constant; this change also updates logging functions to use the modern \any\ type and simplifies test infrastructure by adopting \logtest\.

rest/internal · high confidence

Refactored etcd discovery internals and migrated to Uber mockgen

The internal service discovery implementation has been restructured to improve stability and maintainability. The legacy round-robin and consistent hash balancers have been removed in favor of a simplified registry model that manages etcd client connections and key watchers directly. Authentication and TLS configuration for etcd clusters are now handled via a dedicated account manager. Additionally, the codebase has migrated from \github.com/golang/mock\ to \go.uber.org/mock\, updated the etcd client import path to \go.etcd.io/etcd/client/v3\, and replaced the legacy \interface{}\ type with the modern \any\ alias throughout the internal interfaces and mocks.

core/discov/internal · high confidence

Refactored goctl path and home directory utilities

The \tools/goctl/util/pathx\ package has been rewritten to improve path resolution and home directory management. It now introduces a \RegisterGoctlHome\ API to allow explicit configuration of the goctl home directory (defaulting to \\~/.goctl\), and implements a \GetTemplateDir\ function that ensures backward compatibility by checking for legacy versioned template directories before falling back to the new structure. Additionally, the package adds robust symlink resolution via a new \ReadLink\ function (with a Windows polyfill) and provides utilities to locate project roots by traversing upwards for \go.mod\ files, enhancing reliability when \goctl\ commands are executed in nested directory structures.

tools/goctl/util/pathx · high confidence

Refactors search tree API and error handling for Go 1.18+ compatibility

The search tree implementation in core/search has been updated to use the Go 1.18+ 'any' type alias instead of 'interface{}' for route items and results. Error handling has been refactored to use 'errors.Is' for checking specific error conditions (such as duplicate items or invalid paths) rather than direct equality checks, and error variables have been made unexported. Additionally, the internal traversal logic for searching routes has been optimized by replacing nested loops with a new 'forEach' helper method on nodes, and the build tag syntax has been updated to the modern '//go:build' format.

core/search · high confidence

Removal of MilliTime BSON integration

The \MilliTime\ type in the \core/jsontype\ package no longer supports MongoDB BSON serialization or deserialization. The \GetBSON\ and \SetBSON\ methods have been removed, meaning \MilliTime\ instances will no longer automatically convert to or from MongoDB BSON timestamps. This change also removes the dependency on the \github.com/globalsign/mgo/bson\ package for this type.

core/jsontype · high confidence

Removal of custom tracing interfaces and constants

The custom tracing specification in core/trace/tracespec has been removed, deleting the SpanContext and Trace interfaces as well as the TracingKey constant. This change eliminates the self-designed tracing implementation in favor of the new OpenTelemetry integration, meaning users relying on these specific internal interfaces or the 'X-Trace' context key will need to migrate to the new standard.

core/trace/tracespec · high confidence

Remove ShrinkDeadline and update Go 1.18+ type syntax

The \ShrinkDeadline\ helper in \core/contextx\ has been removed because its behavior is identical to the standard library's \context.WithTimeout\, allowing users to replace calls with the standard function. Additionally, the \unmarshaler.go\ file now uses the \any\ type alias instead of \interface{}\ to align with Go 1.18+ standards, and the internal package import path has been updated to \github.com/zeromicro/go-zero/core/mapping\.

core/contextx · high confidence

Renamed sharedcalls to singleflight and modernized syncx types

The \sharedcalls\ component in \core/syncx\ has been renamed to \singleflight\, updating the \SharedCalls\ interface to \SingleFlight\ and the constructor to \NewSingleFlight\. This change is accompanied by a migration from the generic \interface{}\ type to the Go 1.18+ \any\ alias across the entire \syncx\ package (including \ImmutableResource\, \ManagedResource\, \Pool\, and \LockedCalls\). Additionally, \ImmutableResource.Get()\ now uses a double-checked locking pattern to prevent concurrent fetches, and \ResourceManager\ now sets its internal resources map to nil on close to prevent use-after-close errors.

core/syncx · high confidence

Replaces stringx keyword matching with Aho-Corasick algorithm and adds custom mask support

The \core/stringx\ package now uses the Aho-Corasick algorithm for keyword detection in \Trie\ and \Replacer\, replacing the previous naive tree traversal. This change improves performance and correctness for overlapping or complex keyword patterns. Users can now customize the masking character used by \Trie.Filter\ via the new \WithMask\ option (defaulting to \\*\). Additionally, \Replacer.Replace\ has been updated to handle overlapping matches by performing up to two replacement passes to ensure longest-match priority and prevent infinite loops, and \Filter\ now leverages \strings.Map\ for better efficiency.

core/stringx · high confidence

Router refactoring and enhanced error handling

The router implementation has been refactored to improve error handling and code organization. The \NewPatRouter\ constructor is renamed to \NewRouter\, and the internal \PatRouter\ struct is now unexported (\patRouter\). New exported errors \ErrInvalidMethod\ and \ErrInvalidPath\ are introduced for better error inspection. The router now supports setting a custom handler for 'Method Not Allowed' responses via \SetNotAllowedHandler\, in addition to the existing \SetNotFoundHandler\. Path variables are now managed via the \pathvar\ package instead of raw context values, and the \Vars\ function is removed in favor of \pathvar.Vars\. The router is also moved from \core/httprouter\ to \rest/router\.

rest/router · high confidence

SQL model code generation templates are centralized and versioned

The SQL model code generation logic now uses a centralized template system where individual template files (such as those for variables, types, tags, and CRUD methods) are embedded directly into the Go binary. This change ensures that the generated model code includes a header with the specific goctl version used, improving traceability and consistency for users relying on the goctl tool to generate database models.

tools/goctl/model/sql/template · high confidence

Server interceptors migrated to zrpc with OpenTelemetry tracing and configurable timeouts

The server interceptors have been moved from the legacy core/rpc path to zrpc/internal/serverinterceptors, reflecting the module rename from rpcx to zrpc. The tracing interceptor now uses OpenTelemetry instead of the previous self-designed tracing system, and the prometheus interceptor has been updated to use the new package import paths and adjusted metric buckets. Additionally, a new timeout interceptor has been added that supports both global default timeouts and per-method specific timeouts, while the stat interceptor now accepts a static configuration struct for slow thresholds and ignored methods, replacing the previous global setter functions.

zrpc/internal/serverinterceptors · high confidence

Service configuration and lifecycle management overhaul

Service initialization now integrates OpenTelemetry tracing, a development server, and continuous profiling via new configuration fields in ServiceConf, replacing the previous log.Fatal error handling with structured logging. The service group startup and shutdown logic has been updated to reverse the service stop order and use Go 1.21's sync.OnceFunc, ensuring more predictable lifecycle management and preventing closure variable issues in goroutines.

core/service · high confidence

Simplifies time API and standardizes ticker timeout errors

The \core/timex\ package removes the \Time()\ function, encouraging users to rely on standard \time.Now()\ and \time.Since()\ for better performance and simplicity. The \FakeTicker\ implementation is updated to use \time.Now()\ instead of the removed \Time()\ function, and the \Wait\ method now returns a named \errTimeout\ error instead of a generic error string, providing a consistent error value for timeout scenarios.

core/timex · high confidence

Support for external proto imports with cross-package types

The goctl RPC parser now resolves and parses transitively imported .proto files, allowing RPC request and response types to be qualified with external package names (e.g., base.Req). This enables cross-package type references in service definitions, with the parser collecting metadata for all imported protos to support code generation.

tools/goctl/rpc/parser · high confidence

Trace module rewritten to use OpenTelemetry

The core/trace package has been completely replaced with an OpenTelemetry-based implementation. The previous custom tracing system, including the Span, NoopSpan, and Propagator types, has been removed and replaced with a new agent architecture that initializes a global TracerProvider via StartAgent. This change introduces support for multiple exporters (Zipkin, OTLP over gRPC and HTTP, and file output), allows configuration of OTLP headers and HTTP paths, and enforces single initialization using sync.Once to prevent conflicts in multi-server processes. Additionally, the module now handles W3C TraceContext and Baggage propagation natively and provides utility functions for extracting trace and span IDs from context.

core/trace · high confidence

Updated discovery target format for Go 1.26 compatibility

The zrpc resolver now constructs discovery targets by placing etcd hosts in the URI path rather than the authority section. This change ensures compatibility with Go 1.26, which enforces RFC 3986 and rejects comma-separated hosts in the authority. Users will see discovery targets formatted as \etcd:///host1:port,host2:port?key=\<key\>\ instead of the previous structure, preventing resolution errors on newer Go versions.

zrpc/resolver · high confidence

Version comparison API refactored to support operators and normalized parsing

The \CompareVersions\ function in \core/utils\ has been changed from returning an integer comparison result to accepting a version operator (e.g., \==\, \\<\, \\>\, \\<=\, \\>=\) and returning a boolean. The underlying comparison logic now normalizes version strings by stripping 'V' prefixes and converting hyphens to dots before parsing, and the function signature change requires callers to pass the operator as the second argument. Additionally, the unused \Report\ utility function has been removed, and the \times\ module has been updated to use the fully qualified \github.com/zeromicro/go-zero/core/timex\ import path.

core/utils · high confidence

go-zero core/stat: module rename, Go 1.18+ compatibility, and configurable logging

The core/stat package has been migrated to the github.com/zeromicro/go-zero module path. To support Go 1.18+, the code replaces \interface{}\ with \any\ and updates build tags to the \//go:build\ syntax. The alerting mechanism now uses \logx.Alert\ instead of the removed \utils.Report\. Additionally, stat logging and usage reporting are now conditionally enabled via a new \logEnabled\ flag (exposed as \DisableLog()\), allowing users to suppress these logs. The \printUsage\ function has been refactored to use the \runtime/metrics\ API for more accurate memory statistics, and the remote writer now explicitly sets the JSON content type.

core/stat · high confidence

goctl API command-line interface migrated to Cobra

The goctl API tooling has switched its underlying command-line framework from the previous implementation to Cobra. This change restructures how subcommands (such as dart, doc, format, go, new, plugin, ts, swagger, and validate) are registered and configured, providing a more standard and robust CLI experience for users generating API code, documentation, and configurations.

tools/goctl/api · high confidence

goctl API parser refactored to g4 grammar with strict validation

The goctl API parser has been rewritten to use a g4 grammar, introducing stricter validation for API definitions. Users will now encounter errors for duplicate service declarations, duplicate routes, duplicate type definitions, and circular imports. The parser also enforces that every route has a valid handler and that service metadata keys are unique. This change improves the reliability of API file parsing by catching configuration errors early.

tools/goctl/api/parser/g4/ast · high confidence

goctl API parser regenerated with ANTLR 5 and split into multiple files

The goctl API parser has been regenerated using the ANTLR 5 library (imported from github.com/zeromicro/antlr), replacing the previous version. To prevent memory overflow issues during goctl installation, the generated parser code has been split into multiple files (apiparser\_parser1.go through apiparser\_parser6.go). The underlying grammar (ApiLexer.g4 and ApiParser.g4) remains consistent, defining the syntax for API specifications including types, services, and routes.

tools/goctl/api/parser/g4/gen · high confidence

goctl CLI help text is now externalized to JSON configuration

The goctl command-line interface now loads its help text (short descriptions, long descriptions, examples, and flag usage strings) from an embedded JSON configuration file (\default\_en.json\) rather than having them hardcoded in the Go source. This change introduces a new \cobrax\ wrapper around the Cobra library and a \flags\ package that resolves these strings, supporting template variables for reuse (e.g., reusing the \dir\ description across multiple subcommands). For users, this means the CLI help output is now data-driven, which simplifies maintaining and potentially localizing the tool's documentation without requiring code changes to the command logic.

tools/goctl/internal/flags · high confidence

goctl CLI restructured with Cobra and enhanced help output

The goctl command-line interface has been migrated to the Cobra framework, introducing a new root command structure that registers subcommands for API, gateway, model, RPC, and other generation tools. This change brings support for built-in shorthand flags, Windows-compatible colored output via the gookit/color library, and custom usage templates that render help text with color-coded sections for usage, aliases, examples, and flags. Additionally, shell completion support via Fig is integrated into the command hierarchy.

tools/goctl/cmd · high confidence

goctl SQL model generator refactored with PostgreSQL support

The SQL model code generation logic in \tools/goctl/model/sql/gen\ has been restructured into distinct, single-responsibility files (such as \insert.go\, \update.go\, \findone.go\, and \customized.go\) to improve maintainability. This change introduces native support for PostgreSQL, enabling the generator to produce correct parameter placeholders (\$1\, \$2\ instead of \?\) and properly quote table/column names for PostgreSQL databases via the \WithPostgreSql\ option. The refactoring also standardizes cache key generation and interface method output across all CRUD operations.

tools/goctl/model/sql/gen · high confidence

goctl SQL model templates refactored with session support and cache options

The SQL model code generation templates in tools/goctl/model/sql/template/tpl have been restructured to support new configuration options. Generated models now accept cache.Options via the NewXXXModel constructor, allowing finer control over caching behavior. Additionally, models without caching enabled now expose a withSession method, enabling users to switch the underlying database session for specific operations. The template structure has also been updated to standardize variable naming and improve consistency across generated code.

tools/goctl/model/sql/template/tpl · high confidence

goctl api format now supports stdin input and experimental formatting

The goctl api format command now accepts API definitions from standard input via the -stdin flag, allowing users to pipe formatted output directly without writing to a file first. Additionally, when the experimental mode is enabled, the tool uses a new underlying parser (apiF.Source) for formatting, which may offer improved handling of certain API structures compared to the legacy path.

tools/goctl/api/format · high confidence

goctl api swagger: comprehensive rewrite with custom auth, inline expansion, and example support

The swagger generation tool in tools/goctl/api/swagger has been rewritten to support custom authentication via the new \securityDefinitionsFromJson\ info property and \authType\ server annotation, allowing users to define and reference custom security schemes. The generator now correctly expands inline pointer members and complex nested structs (including arrays and maps of objects) into the Swagger output, fixing previous issues where these types were not fully represented. Additionally, the \example\ tag option is now correctly emitted for path, form, and header parameters, and users can specify the output filename and choose between JSON or YAML formats via the \--filename\ and \--yaml\ flags. The tool also restores API summaries from \@doc\ blocks and correctly handles PUT, PATCH, and DELETE methods for request body definitions.

tools/goctl/api/swagger · high confidence

goctl kube deploy now supports target port, image pull policy, and service account configuration

The \goctl kube deploy\ command has been enhanced to allow users to specify a \targetPort\ for Kubernetes Services, set an \imagePullPolicy\ for container images, and assign a \serviceAccountName\ to the generated Deployment and CronJob resources. These new flags provide finer control over how the generated Kubernetes manifests handle traffic routing, image pulling behavior, and pod identity.

tools/goctl/kube · high confidence

goctl model command restructured with new flags and subcommands

The goctl model command has been reorganized to support more granular control over code generation. Users can now use the --ignore-columns flag to exclude specific columns (defaulting to common timestamp fields) and the --prefix flag to set custom cache key prefixes for both MySQL and PostgreSQL models. The PostgreSQL subcommand introduces a --strict flag for stricter validation. Additionally, the MongoDB generator now supports an --easy flag for simplified declarations and allows custom cache prefixes. The table argument for data source commands has changed from a single string to a slice, allowing multiple tables to be specified at once.

tools/goctl/model · high confidence

goctl model sql command restructured with new CLI flags and test coverage

The SQL model generation command in goctl has been restructured to support modern CLI patterns and enhanced configuration. The command now utilizes the Cobra library for argument parsing and introduces several new flags: \--ignore-columns\ to exclude specific columns from generated models, \--strict\ for stricter validation, and \--cache-prefix\ to define custom prefixes for generated cache keys. It also supports globbing patterns for table names via the \--table\ flag and allows specifying the PostgreSQL schema with \--schema\. The implementation includes validation to ensure a cache prefix is provided when caching is enabled. Additionally, unit tests have been added to verify the table pattern matching logic and DDL generation behavior.

tools/goctl/model/sql/command · high confidence

goctl rpc commands migrate to Cobra CLI with expanded configuration options

The goctl RPC generation commands (rpc new, rpc template, and rpc protoc) have been rewritten to use the Cobra library, replacing the previous flag parsing mechanism. This change introduces several new command-line flags that allow users to customize code generation: --go\_opt and --go-grpc\_opt for passing options to protoc plugins, --module to set the Go module name, --name-from-filename to derive service names from proto filenames, --client to control RPC client generation, --style for output file naming, --verbose for detailed logging, and --remote/--branch for fetching templates from external Git repositories. The rpc protoc command now explicitly requires --go\_out, --go-grpc\_out, and --zrpc\_out flags to define output directories, and supports multiple proto paths and plugins.

tools/goctl/rpc/cli · high confidence

zRPC client now defaults to non-blocking dialing and supports consistent hash load balancing

The zRPC client configuration has changed so that dialing is non-blocking by default (RpcClientConf.NonBlock defaults to true), aligning with gRPC best practices and preventing startup hangs if the server is unavailable. Additionally, a new consistent hash load balancer is available (configurable via RpcClientConf.BalancerName), allowing requests with the same hash key to be routed to the same backend instance for session affinity. The client also exposes helper functions like SetHashKey to inject the hash key into the context for this purpose.

zrpc · high confidence

zrpc client and server internal refactoring with configurable middlewares and health checks

The zrpc/internal package has been restructured to provide a cleaner separation of client and server logic. The client now supports configurable middleware chains (tracing, duration, prometheus, breaker, timeout) via ClientMiddlewaresConf and allows custom unary and stream interceptors. The server now integrates gRPC health checking by default when enabled, registers the health service, and manages graceful shutdown more robustly. Additionally, the server sets a default connection idle time of 5 minutes and uses the new gRPC transport credentials API.

zrpc/internal · high confidence

Fixes

API parser now resolves inline struct tags in nested and recursive types

The goctl API parser in tools/goctl/api/parser now correctly resolves tag members (such as header or path tags) for types that use inline struct embedding, including pointer receivers, nested embeddings, and recursive self-references. This ensures that when parsing API definitions with complex type structures, the parser accurately identifies and processes field tags defined in embedded structs, preventing errors in code generation for these scenarios.

tools/goctl/api/parser · high confidence

Support for new etcd target URL format in RPC resolver

The RPC resolver now supports a new URL format for etcd discovery where hosts are specified in the URL path (e.g., \etcd:///host1:port,key\) rather than the authority section. This change ensures compatibility with stricter URL parsing in Go 1.26 and allows for multiple hosts to be specified in the path. The legacy format (\etcd://host:port/key\) remains supported for backward compatibility. This affects how the resolver extracts host information and keys from target URLs.

zrpc/resolver/internal/targets · high confidence

Test coverage

Added SQL test data for user model parsing; Added mock SQL implementation for testing goctl model generation; Added regression test suite for goctl code generation; Added regression tests for goctl RPC code generation with external proto imports; Added test infrastructure and integration tests for goctl; Added tests for goctl API spec parsing and validation logic; Added unit tests for generated SQL models; Added unit tests for the goctl API G4 parser.

Dependencies

Updated dependencies and upgraded Go version to 1.25

The go-zero framework and goctl tooling have been updated to require Go 1.25. This release includes significant dependency upgrades, most notably upgrading the MongoDB driver to v2 (go.mongodb.org/mongo-driver/v2 v2.8.2) and the Redis client to v9 (github.com/redis/go-redis/v9 v9.22.0). Other key updates include upgrading gRPC to v1.83.2, the OpenTelemetry SDK to v1.46.0, and Kubernetes client libraries to v0.34.3. The goctl module now has its own go.mod file, isolating its dependencies from the main framework.

(dependencies) · high confidence

Housekeeping

Added documentation comment to InternalIp function; Added documentation comments to cmdline input functions.

Written by watchdog.canine.dev from the codebase's own history, inside the signed delivery this page is composed from.

How this codebase got here

Score

  • CAI 61 → 63 (+1.9)
  • Rubric changed (rubric-2026.08.19 → rubric-2026.09.15) — scores are not directly comparable.

Lenses

  • Code Health 99 → 98 (-0.4)
  • Architecture 100 → 80 (-20.0)
  • Maturity 68 → 71 (+2.5)
  • Readiness 63 → 60 (-2.5)
  • Security 48 → 56 (+7.9)

Resolved (54)

  • Coverage not included — suite not readable by the collector
  • Critical CVE: [GHSA redacted] (go.mod)
  • Critical CVE: [GHSA redacted] (go.mod)
  • Dependency hygiene not measured — dependency manifest found but not parsed for hygiene
  • Duplicated block (10 lines × 2) (core/stores/redis/redis.go)
  • Duplicated block (10 lines × 2) (core/stores/redis/redis.go)
  • Duplicated block (10 lines × 2) (zrpc/internal/clientinterceptors/tracinginterceptor.go)
  • Duplicated block (11 lines × 2) (core/logx/writer.go)
  • Duplicated block (12 lines × 2) (core/stores/redis/redisclientmanager.go)
  • Duplicated block (12 lines × 2) (core/stores/sqlx/sqlconn.go)
  • Duplicated block (12 lines × 2) (zrpc/resolver/internal/kube/eventhandler.go)
  • Duplicated block (15 lines × 2) (core/codec/rsa.go)
  • Duplicated block (5 lines × 2) (core/stores/sqlx/orm.go)
  • Duplicated block (6 lines × 2) (zrpc/internal/clientinterceptors/tracinginterceptor.go)
  • Duplicated block (8 lines × 2) (core/prof/runtime.go)
  • Duplicated block (8 lines × 2) (core/stores/redis/redis.go)
  • Duplicated block (9 lines × 2) (core/fx/timeout.go)
  • Duplicated block (9 lines × 2) (core/stores/redis/redis.go)
  • Duplicated block (9 lines × 2) (zrpc/resolver/internal/directbuilder.go)
  • High CVE: [GHSA redacted] (go.mod)
  • …and 34 more

New (307)

  • Deprecated module: github.com/golang/protobuf
  • Deprecated module: go.opentelemetry.io/otel/exporters/zipkin
  • Duplicated block (11 lines × 2) (core/stores/redis/redis.go)
  • Duplicated block (11 lines × 2) (core/stores/redis/redis.go)
  • Duplicated block (11 lines × 2) (core/stores/sqlx/sqlconn.go)
  • Duplicated block (12 lines × 2) (core/prof/runtime.go)
  • Duplicated block (12 lines × 2) (zrpc/internal/clientinterceptors/tracinginterceptor.go)
  • Duplicated block (12 lines × 2) (zrpc/resolver/internal/kube/eventhandler.go)
  • Duplicated block (14 lines × 2) (core/codec/rsa.go)
  • Duplicated block (14 lines × 2) (core/logx/writer.go)
  • Duplicated block (16 lines × 2) (core/stores/redis/redisclientmanager.go)
  • Duplicated block (18 lines × 2) (core/stores/mon/collection.go)
  • Duplicated block (5 lines × 2) (core/stores/redis/metrics.go)
  • Duplicated block (6 lines × 2) (core/stores/mon/collection.go)
  • Duplicated block (6 lines × 2) (core/stores/mon/collection.go)
  • Duplicated block (6 lines × 2) (core/stores/sqlx/orm.go)
  • Duplicated block (7 lines × 2) (core/stores/mon/trace.go)
  • Duplicated block (7 lines × 2) (core/stores/redis/metrics.go)
  • Duplicated block (7 lines × 3) (rest/handler/cryptionhandler.go)
  • Duplicated block (7 lines × 4) (zrpc/internal/clientinterceptors/tracinginterceptor.go)
  • …and 287 more

Changes since last survey

  • 38 commits — 35 feature/other, 3 fixes

By area

  • (root) — 18 commits
  • tools/goctl — 11 commits
  • .github/workflows — 6 commits
  • core/collection — 2 commits
  • core/syncx — 1 commit

Notable commits

  • fix: fix(goctl): support hyphen-only api prefixes (#5747)
  • fix: fix(timingwheel): allow resetting timers after drain (#5753)
  • fix: fix: force refresh every call when refresh interval is 0 (#5746)
  • change: Remove mock data
  • change: chore(deps): bump actions/stale from 10 to 11 (#5716)
  • change: chore(deps): bump github.com/fullstorydev/grpcurl from 1.9.3 to 1.9.4 (#5764)
  • change: chore(deps): bump github.com/go-openapi/spec from 0.21.1-0.20250328170532-a3928469592e to 0.22.11 in /tools/goctl (#5750)
  • change: chore(deps): bump github.com/go-openapi/spec from 0.22.11 to 1.0.0 in /tools/goctl (#5762)
  • change: chore(deps): bump github.com/grafana/pyroscope-go from 1.3.0 to 1.4.2 (#5728)
  • change: chore(deps): bump github.com/jhump/protoreflect from 1.18.0 to 1.18.1 (#5759)
  • change: chore(deps): bump github.com/redis/go-redis/v9 from 9.21.0 to 9.22.0 (#5720)
  • change: chore(deps): bump github.com/stretchr/testify from 1.11.1 to 1.12.1 in /tools/goctl (#5738)
  • change: chore(deps): bump github/codeql-action from 4 to 4.37.4 (#5715)
  • change: chore(deps): bump github/codeql-action from 4.37.4 to 4.37.6 (#5726)
  • change: chore(deps): bump github/codeql-action from 4.37.6 to 4.37.8 (#5743)
  • change: chore(deps): bump github/codeql-action from 4.37.8 to 4.37.9 (#5754)
  • change: chore(deps): bump go.mongodb.org/mongo-driver/v2 from 2.8.0 to 2.8.2 (#5766)
  • change: chore(deps): bump go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp from 1.40.0 to 1.45.0 (#5717)
  • change: chore(deps): bump go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp from 1.45.0 to 1.46.0 (#5765)
  • change: chore(deps): bump go.opentelemetry.io/otel/exporters/stdout/stdouttrace from 1.40.0 to 1.45.0 (#5719)
  • …and 18 more

Written by watchdog.canine.dev from the codebase's own history, inside the signed delivery this page is composed from.

Survey your own repository

zeromicro/go-zero was measured the same way every project in this corpus was: the same rubric, at a pinned commit, with the result published in full. Point a surveyor at a repository you know and see whether you agree with it.

About this page

  • The score is its most recent published measurement, taken on 24 September 2026 at a pinned commit. It is not a live figure and does not change until the project is measured again.
  • Measured at commit 5b1b5bdc3adcc189b3bd8b77f2cc8a363ec3374c — the exact code this score is about.
  • Scored under rubric-2026.09.15 — the same rubric and the same method as every other entry in this index.
  • Measured by watchdog.canine.dev using codehealth-analyzer preprod-5f8d0eb43fd7.