zeromicro/go-zero
 Watch   
 Star   
 Fork   
13 days ago
go-zero

goctl/v1.10.2

What's Changed

goctl

  • Fixed nested client alias generation (#5627) — @puneetdixit200
  • Swagger: added support for custom response status codes (#5691) — @kevwan
  • Swagger: fixed inline pointer member expansion (#5664) — @lxffong
  • Fixed inline struct tag recursion in IsTagMember (#5671) — @014-code

New Contributors

@caltechustc, @Vierblatt, @sapirbaruch, @SAY-5, @jeonghyeon-net, @Meppo, @puneetdixit200, @lxffong, @014-code — thank you for your first contributions! 🎉

13 days ago
go-zero

v1.10.3

Highlights

Core

  • stringx.FirstN: returns empty string for negative n (#5620)
  • stringx.Substr: rejects start > stop to prevent slice panic (#5616)
  • mapping: fixed unmarshaling of pointer-to-slice fields (#5662)
  • collection: optimized queue growth strategy (#5704)

Redis

  • Added XGroupSetID/XGroupSetIDCtx to update a consumer group's last-delivered ID (#5637)
  • Fixed circuit breaker tripping under high concurrency / with incompatible servers (#5654), plus minor refactor (#5666)

Docs

  • Added Korean translations (#5579)

Dependencies

  • go-redis/v9 9.19.0 → 9.21.0
  • mongo-driver/v2 2.6.0 → 2.8.0
  • pelletier/go-toml/v2 2.3.1 → 2.4.3

New Contributors

@Vierblatt, @sapirbaruch, @SAY-5, @jeonghyeon-net, @Meppo, @puneetdixit200, @lxffong, @014-code — thank you for your first contributions! 🎉

Full Changelog: https://github.com/zeromicro/go-zero/compare/v1.10.2...v1.10.3

2026-05-25 19:05:39
go-zero

v1.10.2

New Features

mcp — Opt-in HTTP request metadata bridge for tool handlers (#5550)

Added WithRequestMetadataExtractor option to the MCP server. When set, HTTP request metadata (headers, query parameters, path variables) is captured and injected into each handler's context.Context. Handlers retrieve it via the provided context helpers:

server := mcp.NewMcpServer(conf, mcp.WithRequestMetadataExtractor(mcp.DefaultRequestMetadataExtractor))

server.AddTool(tool, func(ctx context.Context, req *mcp.ServerRequest) (*mcp.ToolResult, error) {
    tenantID, _ := mcp.HeaderFromContext(ctx, "X-Tenant-ID")
    userID, _   := mcp.QueryFromContext(ctx, "user_id")
    // ...
})

Available helpers: RequestMetadataFromContext, HeaderFromContext, QueryFromContext, PathFromContext. Fully backward-compatible — existing NewMcpServer(c) calls are unaffected.

Bug Fixes

discov — Go 1.26 etcd URI compatibility (#5548)

Go 1.26 enforces strict RFC 3986 URI parsing and rejects comma-separated hosts in the URI authority component. BuildDiscovTarget was producing URIs in the form etcd://host1:2379,host2:2379/key, which broke all gRPC services using etcd service discovery with multiple endpoints on Go 1.26+.

The etcd target URL format has been updated to place hosts in the path and the etcd key in a query parameter:

# Before (breaks Go 1.26):
etcd://host1:2379,host2:2379/my-service-key

# After (RFC 3986 compliant, works on all Go versions):
etcd:///host1:2379,host2:2379?key=my-service-key

discov — Unbounded memory growth on duplicate etcd PUT events (#5580)

Fixed two related bugs in discov that caused memory to grow without bound in long-running zRPC services:

  • Redundant OnAdd calls: handleWatchEvents called OnAdd on every etcd PUT event regardless of whether the value changed (e.g. lease refreshes, watch reconnects). Duplicate PUTs are now skipped; value changes fire OnDelete(old) followed by OnAdd(new) to keep listeners consistent.
  • Unbounded slice growth in addKv: Keys were appended to the internal container.values slice unconditionally, causing a single etcd key to accumulate thousands of duplicates over time. addKv now returns early for exact duplicates, and cleans up stale entries when a key moves to a new server address.

New Contributors

Full Changelog: https://github.com/zeromicro/go-zero/compare/v1.10.1...v1.10.2

2026-03-28 23:02:26
go-zero

goctl/v1.10.1

🎉 Highlights

This patch release adds a hasField method for model generation, supports external proto imports with cross-package types in RPC generation, and fixes several bugs.

✨ New Features

  • goctl/model: Add hasField method for model generation (#5484)
  • goctl/rpc: Support external proto imports with cross-package type resolution (#5472)

🐛 Bug Fixes

  • goctl/swagger: Add example field to path/form/header parameters (#5497)
  • goctl: Fix per-service type alias filtering (#5482)
  • goctl: Fix file copy permission missed (#5475)

🧪 Testing

  • Add regression test for per-service type alias filtering (#5483)

🔧 Improvements

  • Upgrade Go version to 1.24 and update dependencies (#5499)

Full Changelog: https://github.com/zeromicro/go-zero/compare/tools/goctl/v1.10.0...tools/goctl/v1.10.1

2026-03-28 22:52:39
go-zero

v1.10.1

🎉 Highlights

This patch release adds JSON5 configuration support, generic Redis command execution via Do/DoCtx, upgrades Go to 1.24, and includes critical security fixes in core/codec.

✨ New Features

  • core/conf: Add JSON5 configuration support (#5433)
  • core/stores/redis: Add Do/DoCtx for generic command execution (#5442)

🐛 Bug Fixes

  • rest/httpc: Reject request body for HEAD method in buildRequest (#5457)
  • core/codec: Critical security fixes (#5479)

🔧 Improvements

  • core: Replace TakeOne usage with cmp.Or (#5461)
  • core/stringx: Replace manual char filter with strings.Map (#5453)
  • core/stores/redis: Reorder Eval/EvalCtx after Do/DoCtx for consistent method ordering (#5502)
  • core/mathx: Add godoc comment to Numerical type constraint (#5470)
  • Upgrade Go version to 1.24 and update dependencies (#5499)

🧪 Testing

  • Add missing edge case tests for CalcEntropy and string utilities (#5471)
  • Add unit tests for Hash, Hash determinism, and Md5Hex edge cases (#5469)

📦 Dependencies

  • Bumped github.com/grafana/pyroscope-go from 1.2.7 to 1.2.8 (#5513)
  • Bumped github.com/pelletier/go-toml/v2 from 2.2.4 to 2.3.0 (#5512)
  • Bumped github.com/alicebob/miniredis/v2 from 2.36.1 to 2.37.0 (#5444)
  • Bumped github.com/modelcontextprotocol/go-sdk from 1.3.0 to 1.3.1 (#5435)
  • Bumped github.com/redis/go-redis/v9 from 9.17.3 to 9.18.0 (#5432)

👥 New Contributors

  • @1911860538 made their first contribution in #5453
  • @amshithnair made their first contribution in #5469
  • @mmfiRan made their first contribution in #5442

Full Changelog: https://github.com/zeromicro/go-zero/compare/v1.10.0...v1.10.1

2026-02-15 19:29:30
go-zero

goctl/v1.10.0

🎉 Highlights

This goctl release brings enhanced Swagger support, improved Docker generation, and better multi-proto file handling.

✨ New Features

  • Proto Package Control: Added cmdline argument to control package name generation from proto filename (#5387)
  • Multi-Proto Support: RPC service now uses proto.Package.Name to support multiple proto files (#5378)

🐛 Bug Fixes

  • Swagger Generation: Fixed support for PUT, PATCH, DELETE methods with request body definitions (#5239)
  • Docker Generation: Ensured Dockerfile includes etc directory and correct CMD based on config (#4343)

🧪 Testing

  • Added comprehensive unit tests for goctl docker command (#5241)

📦 Dependencies

  • Bumped github.com/spf13/cobra from 1.10.1 to 1.10.2 (#5312)
  • Bumped github.com/emicklei/proto from 1.14.2 to 1.14.3 (#5403)

👥 New Contributors

  • @JackGod001 made their first contribution in #4343
  • @stemlaud made their first contribution in #5245
  • @gfischer7 made their first contribution in #5254
  • @lerity-yao made their first contribution in #5270
  • @YunFy26 made their first contribution in #5281
  • @mmfiRan made their first contribution in #5323
  • @mk0walsk made their first contribution in #5375
  • @Bension made their first contribution in #5372

Full Changelog: https://github.com/zeromicro/go-zero/compare/tools/goctl/v1.9.2...tools/goctl/v1.10.0

2026-02-12 22:42:08
go-zero

v1.10.0

🎉 Highlights

This release brings Go 1.23 support, MCP SDK migration, and several important bug fixes including race condition resolutions.

✨ New Features

  • Go 1.23 Support: Upgraded minimum Go version to 1.23 (#5359)
  • MCP Framework: Migrated to official go-sdk with simplified API (#5362)
  • Gateway Enhancement: Exported WithDialer option for custom gRPC client configuration (#5406)

🐛 Bug Fixes

  • Circuit Breaker: Fixed context cancellation incorrectly triggering breaker in httpc (#5360)
  • Service Discovery: Resolved data race in service discovery map access (#5408)
  • Configuration: Fixed support for equal signs in property values (#5392)
  • Configuration: Removed redundant validation (#5372)

🔧 Improvements

  • MCP Routes: Refactored routes and hardened AddTool implementation (#5375)
  • Testing: Added comprehensive validation tests for Load function (#5388)

🗑️ Deprecations

  • Jaeger Exporter: Removed due to official deprecation (#5361)

📦 Dependencies

  • Bumped go.mongodb.org/mongo-driver/v2 from 2.4.1 to 2.5.0 (#5385, #5393)
  • Bumped github.com/alicebob/miniredis/v2 from 2.35.0 to 2.36.1 (#5381, #5386)
  • Bumped github.com/redis/go-redis/v9 from 9.17.2 to 9.17.3 (#5390)
  • Bumped github.com/modelcontextprotocol/go-sdk from 1.2.0 to 1.3.0 (#5413)

👥 New Contributors

  • @mk0walsk made their first contribution in #5375
  • @Bension made their first contribution in #5372

Full Changelog: https://github.com/zeromicro/go-zero/compare/v1.9.4...v1.10.0

2025-12-23 22:45:33
go-zero

v1.9.4

We're excited to announce go-zero v1.9.4! This release includes important improvements, performance optimizations, and new features to enhance your microservices development experience.

New Features

  • Kubernetes EndpointSlice Support: Migrated zrpc kube resolver from deprecated Endpoints API to EndpointSlice API for improved scalability and performance in Kubernetes environments (#4987)
  • Redis GETEX Command: Added support for Redis GETEX command, enabling atomic get-and-expire operations (#5323)

Improvements

  • Logging Improvements:
    • Fixed missing color for levelSevere in log output formatting (#5281)
    • Resolved test log timing and scheduling issues (#5305)
  • Timing Wheel: Added missing Wait() call and improved code clarity in timing wheel implementation (#5315)
  • Service Discovery: Added retry cooldown mechanism in etcd discovery to prevent CPU/disk exhaustion during authentication errors (#5347)
  • Configuration Center: Fixed incorrect value notifications in configuration center updates (#5348)
  • RPC Metrics: Corrected slow threshold priority handling in zrpc stat interceptor (#5310)

Performance Optimizations

  • Optimized getFullName function in configuration module for better efficiency (#5328)
  • Improved bool parsing performance by using strings.EqualFold in mapping module (#5324)

New Contributors

Welcome to our new contributors!

  • @YunFy26 made their first contribution in #5281
  • @mmfiRan made their first contribution in #5323

Full Changelog

For a complete list of changes, see: https://github.com/zeromicro/go-zero/compare/v1.9.3...v1.9.4

2025-11-16 20:36:49
go-zero

v1.9.3

We are excited to announce the release of go-zero v1.9.3! This release brings several important enhancements and bug fixes that improve the framework's reliability, performance, and alignment with industry best practices.

🎉 Highlights

  • Consistent Hash Load Balancing: New gRPC load balancer for session affinity
  • gRPC Best Practices: Changed NonBlock default to align with gRPC recommendations
  • Improved Distributed Tracing: Fixed gateway trace header propagation
  • ORM Improvements: Fixed zero value scanning for pointer destinations

✨ New Features

Consistent Hash Balancer Support (#5246)

Contributor: @zhoushuguang

A new consistent hash load balancer has been added to the zRPC package, enabling session affinity for gRPC services.

Key Features:

  • Hash-based request routing to maintain session affinity
  • Distributes requests based on a hash key from context
  • Minimal request redistribution on node changes
  • Built on go-zero's existing core/hash/ConsistentHash implementation

Usage Example:

// Set hash key in context
ctx := zrpc.SetHashKey(ctx, "user_123")

// Requests with the same key will be routed to the same backend
resp, err := client.SomeMethod(ctx, req)

Configuration:

c := zrpc.RpcClientConf{
    Endpoints: []string{"localhost:8080", "localhost:8081"},
    BalancerName: "consistent_hash",  // Use consistent hash balancer
}

Benefits:

  • Enables stateful service interactions
  • Improves cache hit rates on backend services
  • Reduces session data synchronization overhead
  • Maintains load distribution while supporting affinity

🐛 Bug Fixes

Fixed Gateway Trace Headers (#5256, #5248)

Contributor: @kevwan

Fixed an issue where OpenTelemetry trace propagation headers were not being properly forwarded through the gateway to upstream gRPC services, breaking distributed tracing.

Problem: The gateway was not forwarding critical W3C Trace Context headers (traceparent, tracestate, baggage) to gRPC metadata, causing trace context to be lost at the gateway boundary.

Solution:

  • Enhanced ProcessHeaders function to forward trace propagation headers
  • Headers are now properly converted to lowercase per gRPC metadata conventions
  • Maintains distributed tracing across HTTP → gRPC boundaries

Impact:

  • End-to-end tracing now works correctly through the gateway
  • Improved observability for microservice architectures
  • Better debugging and performance analysis capabilities

Technical Details:

// Trace headers now properly forwarded
var traceHeaders = map[string]bool{
    "traceparent": true,  // W3C Trace Context
    "tracestate":  true,  // Additional trace state
    "baggage":     true,  // W3C Baggage propagation
}

Fixed Multiple Trace Initialization (#5244)

Contributor: @kevwan

Problem: When running multiple services (e.g., REST + RPC) in the same process, the trace agent could be initialized multiple times, potentially causing resource leaks or unexpected behavior.

Solution:

  • Used sync.Once to ensure trace agent is initialized only once
  • Aligned with similar patterns used in prometheus.StartAgent and logx.SetUp
  • Added sync.OnceFunc for shutdown to prevent double cleanup

Code Changes:

var (
    once           sync.Once
    shutdownOnceFn = sync.OnceFunc(func() {
        if tp != nil {
            _ = tp.Shutdown(context.Background())
        }
    })
)

func StartAgent(c Config) {
    if c.Disabled {
        return
    }

    once.Do(func() {
        if err := startAgent(c); err != nil {
            logx.Error(err)
        }
    })
}

Benefits:

  • Prevents resource conflicts in multi-server processes
  • Ensures single global tracer provider instance
  • Safer concurrent initialization
  • Proper cleanup on shutdown

Fixed ORM Zero Value Scanning for Pointer Destinations (#5270)

Contributor: @lerity-yao (first contribution! 🎊)

Problem: When scanning database results into struct fields with pointer types, zero values (0, false, empty string) were not being properly distinguished from NULL values. This caused nil pointers to be set to zero values incorrectly.

Solution: Enhanced the getValueInterface function to properly initialize nil pointers before scanning, ensuring the SQL driver can correctly populate them with zero or non-zero values.

Code Changes:

func getValueInterface(value reflect.Value) (any, error) {
    if !value.CanAddr() || !value.Addr().CanInterface() {
        return nil, ErrNotReadableValue
    }

    // Initialize nil pointer before scanning
    if value.Kind() == reflect.Pointer && value.IsNil() {
        baseValueType := mapping.Deref(value.Type())
        value.Set(reflect.New(baseValueType))
    }

    return value.Addr().Interface(), nil
}

Impact:

type User struct {
    Name    string   `db:"name"`      // Always set
    Age     *int     `db:"age"`       // Can distinguish NULL vs 0
    Active  *bool    `db:"active"`    // Can distinguish NULL vs false
}

// Before: age=0 and age=NULL both resulted in nil pointer
// After:  age=0 → *int(0), age=NULL → nil pointer ✓

Benefits:

  • Correct handling of NULL vs zero values
  • Better semantic representation of optional fields
  • Prevents unexpected nil pointer dereferences
  • Aligns with Go's SQL scanning best practices

🔄 Breaking Changes (With Backward Compatibility)

Changed NonBlock Default to True (#5259)

Contributor: @kevwan

Motivation: Aligned with gRPC official best practices which discourage blocking dials.

Change:

// zrpc/config.go
type RpcClientConf struct {
    // Before: NonBlock bool `json:",optional"`
    // After:
    NonBlock bool `json:",default=true"`  // Now defaults to true
}

Why This Matters:

  1. Blocking dials are deprecated: grpc.WithBlock() is an anti-pattern
  2. Connection state is dynamic: Being connected at dial time doesn't guarantee future connectivity
  3. RPCs handle waiting: All RPCs automatically wait until connection or deadline
  4. Simpler code: No need to check "ready" state before making calls

Migration Guide:

For most users, no action required - the new default is the recommended behavior.

If you explicitly need blocking behavior (not recommended):

// Option 1: Configuration
c := zrpc.RpcClientConf{
    NonBlock: false,  // Explicit blocking
}

// Option 2: Client option (deprecated)
client := zrpc.MustNewClient(c, zrpc.WithBlock())

Backward Compatibility:

  • Existing configs with NonBlock: false continue to work
  • New WithBlock() option available (marked deprecated)
  • No changes needed for services already using NonBlock: true

Documentation: See GRPC_NONBLOCK_CHANGE.md for detailed migration guide and rationale.


👥 New Contributors

We're thrilled to welcome new contributors to the go-zero community! 🎉

  • @JackGod001 - Made their first contribution in #4343
  • @stemlaud - Made their first contribution in #5245
  • @gfischer7 - Made their first contribution in #5254
  • @lerity-yao - Made their first contribution in #5270 (ORM fix)

Thank you for your contributions! We look forward to your continued involvement in the project.


📦 Installation & Upgrade

Install

go get -u github.com/zeromicro/go-zero@v1.9.3

Update

# Update go.mod
go get -u github.com/zeromicro/go-zero@v1.9.3
go mod tidy

🔗 Links


📝 Detailed Changes

Core Enhancements

Load Balancing

  • Added consistent hash balancer for gRPC (zrpc/internal/balancer/consistenthash)
  • Context-based hash key API: SetHashKey() and GetHashKey()
  • Configurable replica count and hash function
  • Comprehensive test coverage

Distributed Tracing

  • Fixed trace header propagation in gateway
  • Proper handling of W3C Trace Context headers
  • Case-insensitive header matching per gRPC conventions
  • Single initialization with sync.Once pattern

ORM/Database

  • Fixed pointer field scanning for zero values
  • Proper NULL vs zero value distinction
  • Enhanced getValueInterface() with nil pointer initialization
  • Support for sql.Null* types

gRPC Client

  • Changed NonBlock default to true
  • Added deprecated WithBlock() option for compatibility
  • Explicit handling of both blocking and non-blocking modes
  • Updated client initialization logic

Testing & Quality

  • Added comprehensive test coverage for all changes
  • Edge case handling in ORM tests
  • Gateway trace header test cases
  • Consistent hash balancer benchmarks

🙏 Acknowledgments

Special thanks to all contributors, issue reporters, and community members who made this release possible. Your feedback and contributions continue to make go-zero better!


💬 Feedback

If you encounter any issues or have suggestions for future releases, please:

Happy coding with go-zero! 🚀

2025-10-12 11:55:57
go-zero

goctl/v1.9.2

What's Changed

  • Swagger Improvements:

    • Fix swagger path generation: remove trailing slash for root routes with prefix #5212 (@Copilot)
    • Fix swagger generation: info block and server tags not included #5215 (@Copilot)
    • Restore API summaries in swagger generation #5237 (@kevwan)
  • Other Fixes:

    • Fix: issue #5154, not using SSE template files #5220 (@kevwan)

New Contributors

  • @rizkyikiw42 made their first contribution in #5210
  • @ZH1995 made their first contribution in #5233

Full Changelog: tools/goctl/v1.9.1...tools/goctl/v1.9.2