go-kratos/kratos
57.7
Adequate · 13 November 2026
19.2k
lines of production code
Go
primary language
8
measurements over time
What this system is
Features
Add Apollo config source for Kratos v3
Introduces a new \config.Source\ implementation for the Apollo configuration center, enabling Kratos applications to load and watch configuration from Apollo namespaces. The module supports JSON, YAML, YML, and properties formats, and includes options for enabling configuration backup, specifying the app ID, cluster, endpoint, and secret. It also provides a watcher mechanism to receive real-time configuration updates and handles edge cases such as nil values during deletion to prevent panics.
contrib/config/apollo, contrib/config/polaris · high confidence
Add Consul configuration provider
Introduces a new configuration source for HashiCorp Consul in the \contrib/config/consul\ package. Users can now load configuration key-value pairs from a specified Consul path and watch for changes in real-time. The provider automatically detects the configuration format (e.g., JSON, YAML) based on the file extension of the Consul keys and skips empty keys during loading.
contrib/config/consul · high confidence
Add Discovery registry integration for service registration and discovery
Introduces a new registry implementation in contrib/registry/discovery that integrates with the bilibili/discovery service. This module provides a Registrar and Discovery interface, allowing Kratos services to register themselves with region, zone, and environment metadata, and enabling clients to discover and watch service instances via the discovery server. The implementation handles instance registration, automatic renewal, deregistration, and zone-aware service discovery.
contrib/registry/discovery · high confidence
Add Eureka service registry integration
Introduces a new Eureka registry implementation for the Kratos framework, enabling service registration, discovery, and health-check heartbeats via the Eureka API. The change adds the \contrib/registry/eureka\ package (client, API, registry, and watcher components) and includes integration tests to verify registration, deregistration, and service watching workflows.
contrib/registry/eureka · high confidence
Add HTTP and gRPC status code conversion utilities
The transport/http/status package now provides a default converter that maps between HTTP status codes and gRPC error codes, enabling consistent error handling across HTTP and gRPC transports. The converter includes mappings for standard codes (e.g., 400 Bad Request to InvalidArgument, 500 Internal Server Error to Internal) and supports the non-standard HTTP 499 Client Closed code, mapping it to gRPC Canceled. Users can utilize the ToGRPCCode and FromGRPCCode functions to translate status codes in either direction.
transport/http/status · high confidence
Add JSON and MsgPack encoding codecs
New JSON and MsgPack codecs are now available in the contrib/encoding module. The JSON codec supports marshaling and unmarshaling for standard Go types, types implementing json.Marshaler/json.Unmarshaler, and protobuf messages (using protojson with configurable options like EmitUnpopulated and DiscardUnknown). The MsgPack codec provides binary serialization via the msgpack/v5 library. Both codecs are automatically registered with the encoding framework upon initialization.
contrib/encoding · high confidence
Add JSON codec implementation and registration
Introduces a new JSON codec in the \encoding/json\ package that registers itself with the framework's codec registry. This codec implements the standard \encoding\ interface, delegating marshaling and unmarshaling to the Go standard library while respecting custom \json.Marshaler\ and \json.Unmarshaler\ interfaces on user types. A corresponding test suite validates the correct handling of standard structs, embedded types, and custom JSON implementations.
encoding/json · high confidence
Add Kratos v3 error code extension definitions
A new protocol buffer definition file has been added to the third-party errors module, introducing extensions for Google Protobuf enum options to support custom error codes (default\_code and code) as defined by the Kratos v3 library.
_third\party/errors · high confidence
Add Kubernetes Config Source
Users can now load configuration from Kubernetes ConfigMaps using the new \contrib/config/kubernetes\ package. This feature allows applications to read ConfigMaps by specifying a namespace and optional label or field selectors, supporting both in-cluster execution (via service accounts) and out-of-cluster execution (via a local kubeconfig file). The implementation includes a watcher to detect changes to ConfigMaps in real-time.
contrib/config/kubernetes · high confidence
Add Kubernetes-based service registry for Kratos
Introduces a new Kubernetes registry implementation in \contrib/registry/kubernetes\ that enables service discovery and registration directly against Kubernetes pods. The registry uses pod labels (e.g., \kratos-service-id\, \kratos-service-app\) and annotations (e.g., \kratos-service-metadata\, \kratos-service-protocols\) to track service instances, allowing Kratos applications to register themselves and discover peers within a Kubernetes cluster. Includes unit tests to verify registration, deregistration, and service watching capabilities.
contrib/registry/kubernetes · high confidence
Add MCP transport support
Users can now integrate the Model Context Protocol (MCP) into their Kratos applications. This change introduces a new \contrib/transport/mcp\ module that provides an MCP server implementation, allowing developers to register tools and handle requests via HTTP/SSE. The module includes a \NewServer\ constructor for configuring the server address, middleware, and options, along with standard \Start\ and \Stop\ lifecycle methods to manage the server within a Kratos application.
contrib/transport · high confidence
Add OAuth2 middleware for client and server authentication
A new OAuth2 middleware is available in contrib/middleware/oauth2 for both HTTP and gRPC transports. The client middleware automatically fetches access tokens from a provided TokenSource, caches them, and injects them into the Authorization header. The server middleware validates incoming bearer tokens using a configurable Validator (including a built-in RFC 7662 introspection validator with optional caching) and stores the resulting TokenInfo in the context for use by handlers. It also includes a scope-checking middleware to enforce specific scopes per operation, returning standard RFC 6750 WWW-Authenticate challenges on failure.
contrib/middleware/oauth2 · high confidence
Add OpenSergo metadata reporting integration
Introduces a new OpenSergo contrib module that allows Kratos applications to report service metadata to an OpenSergo endpoint. The implementation scans registered Protobuf descriptors to extract service and type information, including HTTP paths and methods, and sends this data via the OpenSergo gRPC MetadataService. Configuration is supported through environment variables (OPENSERGO\_ENDPOINT, OPENSERGO\_BOOTSTRAP, OPENSERGO\_BOOTSTRAP\_CONFIG) or explicit options, enabling users to integrate their services with OpenSergo for service discovery and governance.
contrib/opensergo · high confidence
Add P2C (Pick of 2 Choices) load balancer selector
A new P2C load balancer is now available in the service discovery selector package, allowing users to distribute traffic by randomly picking two nodes and selecting the one with the higher weight. The implementation includes a forced-pick mechanism that selects an unchosen node if it has not been picked within a 3-second window, helping to trigger health status updates. The selector is registered under the name "p2c" and is built using the EWMA node builder.
selector/p2c · high confidence
Add Polaris service governance integration
The contrib/polaris package now provides a complete service governance integration for Kratos, adding support for service registry and discovery, dynamic configuration management with file watching, rate limiting, and intelligent routing. Users can register and discover services, load and watch configuration files from Polaris, apply rate limits via a middleware, and filter service nodes based on routing rules.
contrib/polaris · high confidence
Add Sentry middleware for error tracking in Kratos
Users can now integrate Sentry into their Kratos applications via a new middleware located in contrib/errortracker/sentry. This middleware automatically captures panics from HTTP and gRPC servers and reports them to Sentry, supporting configuration for custom tags, context-based tags (such as trace IDs), re-panic behavior, and delivery timeouts. It is designed to work alongside existing recovery and tracing middlewares to provide comprehensive error reporting.
contrib/errortracker · high confidence
Add Servicecomb registry integration for Kratos v3
Users can now register and discover services with Huawei Cloud ServiceComb using the Kratos v3 registry interface. This change introduces a new \contrib/registry/servicecomb\ package that implements \registry.Registrar\ and \registry.Discovery\, allowing applications to use the ServiceComb client for service registration, heartbeat management, and instance watching. The implementation includes a watcher for real-time service instance updates and is accompanied by unit tests and usage examples in the README.
contrib/registry/servicecomb · high confidence
Add Tencent Polaris service registry integration
Users can now register and discover services using Tencent Polaris as a service registry. This change introduces a new \Registry\ implementation in \contrib/registry/polaris\ that adheres to the standard \registry.Registrar\ and \registry.Discovery\ interfaces, allowing applications to leverage Polaris for service registration, health checking, and instance discovery via the Polaris Go SDK.
contrib/registry/polaris · high confidence
Add Weighted Round Robin (WRR) load balancer
Introduces a new WRR balancer in the selector package that distributes requests to service instances based on their weights, following the nginx WRR algorithm. The implementation includes logic to automatically clean up stale weight entries from the internal state map when the available node list changes, ensuring accurate load distribution as services scale up or down.
selector/wrr · high confidence
Add YAML encoding codec
A new YAML codec has been added to the encoding package, allowing users to marshal and unmarshal data using the gopkg.in/yaml.v3 library. The codec is automatically registered under the name "yaml" via an init function, enabling seamless integration with the framework's existing encoding infrastructure for YAML-based data exchange.
encoding/xml, encoding/yaml · high confidence
Add \`kratos proto server\` command to generate server-side gRPC implementations
The \kratos\ CLI now includes a \proto server\ subcommand that parses \.proto\ files and generates Go server-side service implementations. This feature supports unary, server-streaming, client-streaming, and bidirectional-streaming RPCs, correctly handling nested message types and the \google.protobuf.Empty\ type. The generated code is written to a specified target directory (defaulting to \internal/service\), with unit tests provided to verify service name parsing and parameter naming logic.
cmd/kratos/internal/proto/server · high confidence
Add client-side circuit breaker middleware
Introduces a new client-side circuit breaker middleware that protects downstream services by rejecting requests when the circuit is open. The middleware automatically tracks success and failure rates for each operation, marking requests as failed on internal server errors, service unavailable errors, or gateway timeouts, and exposes a specific error (ErrNotAllowed) to indicate when a request is rejected due to the circuit breaker state.
middleware/circuitbreaker · high confidence
Add command for generating proto API templates
The \kratos proto add\ command is now available, allowing users to generate standard Protocol Buffer API templates (including service definitions and CRUD messages) from a hierarchical proto file path. The command validates that the input path is hierarchical to prevent panics, handles underscore-to-camel-case conversion for service names, and writes the generated \.proto\ file to the specified directory structure.
cmd/kratos/internal/proto/add · high confidence
Add direct gRPC resolver for static address lists
A new 'direct' resolver has been added to the gRPC transport layer, allowing users to specify a static list of backend addresses directly in the target URI (e.g., \direct://authority/127.0.0.1:9000,127.0.0.2:9000\). This component registers itself with the gRPC resolver package and parses comma-separated addresses from the URL path, updating the client connection state accordingly. Unit tests are included to verify scheme registration and address parsing behavior.
transport/grpc/resolver/direct · high confidence
Add direct node selector implementation
Introduces a new direct node implementation in the selector package, allowing services to route traffic to specific endpoints without load balancing. The \Node\ type implements \selector.WeightedNode\ and \selector.WeightedNodeBuilder\, tracking the last pick timestamp via atomic operations and exposing the elapsed time since the last pick. It supports custom weights from service metadata, defaulting to 100 if none are specified, and provides a \Raw()\ method to access the underlying node.
selector/node/direct · high confidence
Add endpoint URL parsing and scheme handling utilities
Introduces new helper functions in the internal endpoint package to simplify endpoint management: \NewEndpoint\ constructs a URL from a scheme and host, \ParseEndpoint\ extracts the host from a list of endpoint strings matching a specific scheme, and \Scheme\ toggles between secure and insecure variants (e.g., http to https, grpc to grpcs).
internal/endpoint · high confidence
Add environment variable configuration source with optional prefix support
Users can now load configuration directly from environment variables by using the new \config/env\ source. This source supports optional prefixes (e.g., \KRATOS\_\) to filter and strip specific environment keys before loading them into the config tree, and includes a watcher implementation to support configuration updates.
config/env · high confidence
Add etcd configuration source and watcher
This change introduces a new etcd-based configuration source for the Kratos framework, allowing applications to load and watch configuration data stored in etcd. Users can create a source using the etcd client v3, specifying a path and an optional prefix flag to watch key ranges. The implementation includes a watcher that detects changes in the etcd keyspace and returns updated configuration values, supporting automatic config reloading. The feature is accompanied by unit tests verifying loading, watching, and format detection based on file extensions.
contrib/config/etcd, contrib/config/nacos · high confidence
Add file-based configuration source with hot-reload support
Introduces a new file source implementation for the Kratos configuration system, allowing applications to load configuration from local files or directories. The implementation supports automatic hot-reloading via file system watchers, enabling runtime updates without restarting the service. It includes utilities for detecting file formats and handles both single-file and directory-based configuration loading.
config/file · high confidence
Add form encoding codec for URL query parameters
The \encoding/form\ package introduces a new codec that enables serializing and deserializing Go structs and Protocol Buffers into \x-www-form-urlencoded\ format. This allows users to bind URL query parameters directly to request structs, with specific support for Protobuf well-known types (such as \Timestamp\, \Duration\, \FieldMask\, and \BytesValue\) and map fields in query strings.
encoding/form · high confidence
Add kratos changelog command to view release and commit history
Users can now run \kratos changelog\ to retrieve release notes or commit information for the Kratos framework. The command supports fetching the latest release details or specific version tags, and includes a \dev\ mode to display recent commits. It automatically groups commits into categories such as Breaking Changes, New Features, Bug Fixes, Dependencies, Builds, and Chores based on commit message prefixes, and allows customization of the GitHub repository URL and authentication token via flags or environment variables.
cmd/kratos/internal/change · high confidence
Add panic recovery middleware with latency tracking
A new recovery middleware has been introduced to automatically catch panics during request handling. When a panic occurs, the middleware logs the error details (including the stack trace and request data) using the standard \slog\ logger and allows customization via \WithHandler\ and \WithLogger\ options. Additionally, it records the time taken to recover from the panic in the request context under the \Latency\ key, enabling downstream components to observe recovery performance.
middleware/recovery · high confidence
Add proto command to Kratos CLI
The \kratos\ CLI now includes a new \proto\ command for generating Protocol Buffer files. This command serves as a parent for subcommands to add, generate client, and generate server code, integrating these capabilities into the main tool interface.
cmd/kratos/internal/proto · high confidence
Add protobuf codec for encoding/decoding
The \encoding/proto\ package introduces a new protobuf codec that automatically registers itself upon import. This codec implements the \Marshal\ and \Unmarshal\ methods to serialize and deserialize data using \google.golang.org/protobuf/proto\, supporting both direct \proto.Message\ types and pointer-to-struct types via reflection. This enables users to use protobuf as the default transport codec within the Kratos framework.
encoding/proto · high confidence
Add random load balancer selector
Introduces a new random load balancer implementation in the selector package. The new \random\ balancer selects nodes using \math/rand/v2\ and integrates with the existing node and filter infrastructure, allowing users to distribute traffic randomly across available service instances.
selector/random · high confidence
Add rate-limit middleware with configurable limiter support
A new rate-limiting middleware is introduced for the server, allowing requests to be throttled based on a configurable limiter implementation. By default, it uses the internal BBR limiter, but users can provide a custom limiter via the \WithLimiter\ option. When the rate limit is exceeded, the middleware returns a 429 Service Unavailable error (\ErrLimitExceed\). The middleware also supports a \DoneFunc\ callback to record request completion metadata, enabling observability into rate-limited requests.
middleware/ratelimit · high confidence
Add request validation middleware with custom validator support
A new validation middleware is introduced that automatically checks requests implementing a \Validate() error\ method and allows users to register custom validation functions. When validation fails, the middleware returns a \BadRequest\ error with the validation error attached as a cause, enabling better error tracing for API consumers.
middleware/validate · high confidence
Add selector-based middleware matching
A new middleware matcher has been added to the internal/matcher package, allowing users to register middleware for specific operation selectors (including wildcard prefixes like /foo/\*). The matcher applies default middleware globally and then appends selector-specific middleware based on the operation name, enabling more granular control over middleware execution paths.
internal/matcher · high confidence
Add version-based node filtering in service selector
Users can now filter service instances by version using the new \Version\ filter in the selector package. This filter allows routing logic to select only nodes matching a specific version string, enabling precise version-based traffic control.
selector/filter · high confidence
Added 'kratos upgrade' command to update tools via go install
A new 'upgrade' command has been added to the Kratos CLI, allowing users to update Kratos tools and related dependencies using 'go install'. The command installs the latest versions of the kratos CLI itself, the HTTP and error code generators (v3), and standard protobuf/gRPC generators, as well as the OpenAPI generator (protoc-gen-openapi).
cmd/kratos/internal/upgrade · high confidence
Added Google API and Protobuf third-party protocol buffer definitions
The project now includes the standard Google API and Protobuf descriptor files (annotations, client, field\_behavior, http, httpbody, and descriptor.proto) in the third\_party directory. These definitions provide the necessary schema for gRPC transcoding, HTTP REST mappings, and field behavior annotations, enabling the API layer to support both gRPC and REST endpoints and allowing tooling to interpret field constraints like required or output-only status.
_third\party/google · high confidence
Added HTTP content-type utility functions
The internal httputil package now provides helper functions for managing HTTP content types. The new ContentType function constructs a full content-type string by prepending 'application/' to a given subtype, while ContentSubtype extracts the subtype from a full content-type header value, handling optional parameters like charset. Tests have been added to verify the correct parsing and construction of these values.
internal/httputil · high confidence
Added context merging utility
The internal context package now provides a Merge function that combines two Go contexts into a single context. This new capability allows the application to handle multiple cancellation signals or deadlines simultaneously, automatically propagating the first cancellation or error from either parent context while respecting the earliest deadline.
internal/context · high confidence
Added helloworld testdata with v3-compatible generated code
The internal testdata/helloworld directory now includes the proto definition and generated Go code for the Greeter service, updated to target the v3 module path (github.com/go-kratos/kratos/v3). The generated files include protobuf messages (HelloRequest, HelloReply), gRPC client/server stubs, and HTTP handlers that map the SayHello RPC to a GET /helloworld/{name} endpoint, providing a concrete example for testing transport and service layers.
internal/testdata/helloworld · high confidence
Added internal lazy-load container group
The \internal/group\ package now provides a generic, thread-safe lazy-load container (\Group\[T any\]\) that caches objects by key and creates them on demand using a provided factory function. Users can retrieve cached instances via \Get\, clear all cached objects with \Clear\, or reset the container with a new factory and cleared state via \Reset\. This internal utility supports efficient object reuse and lifecycle management within the application.
internal/group · high confidence
Added middleware chaining capability
The middleware package now provides a Chain function that allows multiple middleware components to be composed into a single handler. This enables users to apply a sequence of HTTP/gRPC transport middlewares in a specific order, where each middleware wraps the next, facilitating layered processing such as logging, authentication, or metrics collection.
middleware · high confidence
Added pprof HTTP handler for debugging
A new pprof handler is now available in the transport layer, exposing standard Go profiling endpoints (index, cmdline, profile, symbol, and trace) under the /debug/pprof/ path. This allows users to attach debugging and profiling tools to the application's HTTP server to analyze performance and runtime behavior.
transport/http/pprof · high confidence
Added protoc-gen-validate (PGV) third-party definitions
The \third\_party/validate\ directory now includes the \validate.proto\ schema and README from the \protoc-gen-validate\ (PGV) project. This adds the standard validation rule definitions (such as \FieldRules\, \StringRules\, \Int32Rules\, etc.) and message/field extensions required for integrating PGV-based validation into the protocol buffer compilation pipeline.
_third\party/validate · high confidence
Automated multi-module linting and testing infrastructure
Added shell scripts in the hack directory to automate linting, testing, and code fixing across the project's multiple Go modules. The new tools.sh script provides commands to run golangci-lint, execute tests, and apply automatic fixes, while respecting exclusion lists defined in .lintcheck\_failures and .test\_ignored\_files to manage modules with known issues or specific test requirements.
hack · high confidence
Config module initialization with v3 API and type-aware resolution
The config package has been initialized for the v3 module, introducing a new \Config\ interface and a generic \Get\[T\]\ helper for retrieving configuration values. A key behavioral change is the introduction of \WithResolveActualTypes\, which allows the config resolver to automatically convert placeholder values (like \${ENABLED:true}\) into their native Go types (bool, int, float) rather than leaving them as strings, ensuring compatibility with protojson and other decoders. The module also includes a new \defaultMerge\ function that safely deep-merges configuration maps while cloning source values to prevent aliasing, and provides a \README\ documenting the available external config sources (Kubernetes, Apollo, etcd, Nacos) for the v3 contrib modules.
config · high confidence
Consul registry support for multi-datacenter, custom checks, and service resolution
The Consul registry implementation now supports querying services across multiple datacenters (via the \MULTI\ datacenter mode and \WithDatacenter\ option) and allows users to configure custom health checks, heartbeat intervals, deregistration timeouts, and service tags through new options like \WithServiceCheck\, \WithHeartbeat\, and \WithTags\. Additionally, the registry introduces a \ServiceResolver\ interface (\WithServiceResolver\) that lets users define custom logic for resolving service endpoints from Consul entries, and improves IPv6 compatibility by using \net.JoinHostPort\ for address construction.
contrib/registry/consul · high confidence
HTTP transport layer restructured with new client, context, and binding APIs
The HTTP transport package has been rebuilt from the ground up, introducing a new client architecture with service discovery support, a dedicated Context interface for request handling, and explicit binding functions for query and form data. Users now interact with a \Client\ struct configured via options like \WithEndpoint\ and \WithDiscovery\, while server-side handlers use a \Context\ wrapper that provides methods like \Bind\, \JSON\, and \XML\ for streamlined response writing. The change also includes new utilities for path building with proper escaping and a redirector interface, replacing the previous ad-hoc implementations.
transport/http · high confidence
Initial implementation of the etcd service registry and discovery client
This change introduces the \contrib/registry/etcd\ package, providing a new service registry implementation for the Kratos framework backed by etcd. It enables service registration with automatic heartbeat management (using leases and configurable TTLs) and service discovery via key-based watchers. The implementation uses the service name and ID to form unique keys within a configurable namespace, supports retry logic for registration failures, and includes a watcher that automatically reconnects on errors to maintain service visibility.
contrib/registry/etcd · high confidence
Introduce 'kratos run' command to execute project commands
Adds a new 'kratos run' CLI command that automatically locates the project's cmd directory (searching up to five parent levels) and executes the selected subcommand via 'go run'. The command supports specifying a target working directory with the -w/--work flag and allows passing additional arguments to the program after a double-dash separator.
cmd/kratos/internal/run · high confidence
Introduce EWMA-based weighted node for load balancing
Added a new Exponentially Weighted Moving Average (EWMA) node implementation in the selector package that calculates endpoint weights based on recent latency and error rates. This allows the load balancer to dynamically adjust traffic distribution by favoring nodes with lower response times and fewer errors, while penalizing unhealthy or slow instances.
selector/node/ewma · high confidence
Introduce \`kratos proto client\` command for generating gRPC and HTTP client code
A new \kratos proto client\ subcommand has been added to the CLI, allowing users to generate Go client code (gRPC, HTTP, and error types) from \.proto\ files. The command automatically checks for and upgrades required protoc plugins (such as \protoc-gen-go\, \protoc-gen-go-grpc\, \protoc-gen-go-http\, \protoc-gen-go-errors\, and \protoc-gen-openapi\) if they are missing. It supports processing single proto files or entire directories, respects a configurable \--proto\_path\ (defaulting to \./third\_party\), and automatically includes validation code generation if the \validate/validate.proto\ import is detected.
cmd/kratos/internal/proto/client · high confidence
Introduce discovery-based gRPC resolver with configurable timeout and subset selection
Added a new discovery resolver for the gRPC transport layer that watches service registry instances and updates the gRPC client connection with resolved addresses. The resolver now supports configuring a timeout for watcher creation (exposing a specific timeout error if exceeded), setting an insecure mode to handle scheme conversion, and limiting the number of selected instances via a subset algorithm. It also handles endpoint parsing, deduplication, and attribute mapping from service metadata.
transport/grpc/resolver/discovery · high confidence
Introduce host address extraction utilities
Adds the \internal/host\ package, providing functions to extract host and port from addresses, validate IP reachability, and determine the most suitable local IP address for binding. The \Extract\ function now intelligently selects a valid, non-loopback IP from available network interfaces, preferring IPv4, and returns the address with the port from a listener if the input address is a wildcard (0.0.0.0 or \[::\]).
internal/host · high confidence
Introduce metadata package for request header management
Added a new \metadata\ package that provides a \Metadata\ type (mapping string keys to string slices) to represent and manipulate request headers internally. This includes methods for adding, getting, setting, and retrieving multiple values for keys, as well as a \Clone\ method for deep copying. The package also integrates with Go contexts via \NewServerContext\, \FromServerContext\, \NewClientContext\, \FromClientContext\, and helper functions \AppendToClientContext\ and \MergeToClientContext\ to attach and merge metadata into request contexts.
metadata · high confidence
Introduce middleware selector for conditional middleware application
Adds a new \middleware/selector\ package that allows users to conditionally apply middleware chains based on the request operation. The selector supports filtering by prefix, exact path, regular expression, or a custom match function, and provides separate builders for server-side and client-side transport contexts.
middleware/selector · high confidence
Introduce new selector package with node filtering and peer context support
The \selector\ package now provides a structured service discovery and load-balancing mechanism. It introduces a \Balancer\ interface for picking nodes and a \Default\ selector that applies \NodeFilter\ functions to narrow down candidate nodes before selection. The system supports a global selector configuration via \SetGlobalSelector\ and allows attaching peer information to RPC contexts using \NewPeerContext\ and \FromPeerContext\, enabling downstream components to identify the selected node.
selector · high confidence
Introduce protoc-gen-go-errors v3 for generating Kratos error helpers
The \cmd/protoc-gen-go-errors\ tool has been updated to version 3.0.0, introducing a new code generation pipeline that reads Protobuf enum definitions and produces Go helper functions. Specifically, it generates \Is\<Reason\>\ type-checking functions and \Error\<Reason\>\ constructor functions for each enum value, allowing developers to easily match and create structured errors. The generator now supports custom error codes via \errors.code\ and \errors.default\_code\ extensions, enforces code ranges (0-600), and includes a \case2Camel\ utility to correctly format enum values into Go identifiers. Configuration is managed via new \buf.yaml\, \buf.gen.yaml\, and \buf.lock\ files, and the tool embeds the \errors.proto\ definition for extension support.
cmd/protoc-gen-go-errors · high confidence
Introduce protoc-gen-go-http v3 code generator
The \cmd/protoc-gen-go-http\ plugin has been rewritten for v3, introducing a new code generation engine that produces HTTP server and client interfaces, route registrations, and streaming handlers (WebSocket for client-streaming, SSE for server-streaming) based on \google.api.HttpRule\ annotations. The generator now supports binding query parameters and path variables, handles \google.api.HttpBody\ responses, and includes validation warnings for invalid HTTP method configurations (e.g., GET/DELETE with bodies). It also adds a \.gitignore\ for the compiled binary and version constants.
cmd/protoc-gen-go-http · high confidence
Introduce structured error handling with HTTP/gRPC status mapping
The errors package now provides a structured \Error\ type that wraps HTTP status codes, reasons, and metadata, enabling seamless conversion between HTTP and gRPC status codes. This change introduces helper functions like \BadRequest\, \NotFound\, and \InternalServer\ for common HTTP errors, along with \FromError\ and \GRPCStatus\ to bridge the two protocols. It also supports error chaining via \Unwrap\ and \Is\, allowing developers to inspect and compare errors consistently across HTTP and gRPC boundaries.
errors · high confidence
Introduce transport context and typed transport kind
The transport package now provides a \Transporter\ interface and associated context helpers (\NewServerContext\, \FromServerContext\, \NewClientContext\, \FromClientContext\) to store and retrieve transport metadata within Go contexts. This includes a new strongly-typed \Kind\ enum (supporting \KindGRPC\ and \KindHTTP\) and interfaces for \Server\, \Endpointer\, and \Header\, enabling applications to access transport-specific details like endpoint, operation, and headers directly from the context.
transport · high confidence
Kratos CLI v3.0.0 release with new subcommands
The Kratos CLI tool has been upgraded to version 3.0.0, introducing a new command-line interface structure. Users can now utilize the \kratos run\ command to execute services, the \kratos changelog\ command to view change history, and the \kratos upgrade\ command to update the tool itself, alongside the existing \kratos new\ and \kratos proto\ commands.
cmd/kratos · high confidence
Kratos v3.0.0 release with lifecycle hooks and v2-to-v3 migration
The framework is released as version 3.0.0, introducing explicit lifecycle management via BeforeStart, BeforeStop, AfterStart, and AfterStop hooks that allow users to run custom logic at specific points in the application's startup and shutdown sequences. The release also includes a v2-to-v3 migration guide to help users upgrade, as this version reduces core dependencies and makes previously implicit behaviors explicit.
(repo-wide) · high confidence
New OpenTelemetry and JWT middleware modules in contrib
This release introduces new contrib modules for OpenTelemetry and JWT authentication. The \contrib/otel\ package provides server and client middleware for distributed tracing, metrics, and logging, including a slog handler that automatically correlates logs with trace context and a metadata propagator for service names. The \contrib/middleware/jwt\ package adds a new JWT authentication middleware for both server and client sides, supporting custom claims, signing methods, and parser options.
(repo-wide) · high confidence
New gRPC transport implementation with custom load balancing and JSON codec
The gRPC transport layer has been replaced with a new implementation that introduces a custom 'selector' load balancer for client-side service discovery, a JSON codec for protobuf message serialization, and updated server/client options including TLS, middleware, and health check support.
transport/grpc · high confidence
New metadata propagation middleware for Kratos
Introduces a new middleware package that manages metadata propagation between client and server sides. The server-side middleware extracts HTTP headers with specific prefixes (defaulting to 'x-md-') and merges them with constant metadata into the server context. The client-side middleware injects constant metadata, client-specific metadata, and global metadata (identified by the 'x-md-global-' prefix) into outgoing request headers, while filtering out local-only keys to ensure proper cross-service propagation.
middleware/metadata · high confidence
New structured logging middleware for server and client requests
A new logging middleware has been introduced in the \middleware/logging\ package, providing \Server\ and \Client\ wrappers that log request details using Go's \slog\. The middleware automatically captures the transport kind (e.g., HTTP), operation path, request arguments, response code, reason, and latency. It intelligently formats request arguments by checking for a \Redacter\ interface (to hide sensitive data) or a \fmt.Stringer\ implementation before falling back to a standard struct dump. Errors are logged at the error level with stack traces, while successful requests are logged at the info level.
middleware/logging · high confidence
Redesigned \`kratos new\` command with custom repo support and \`--nomod\` handling
The \kratos new\ command has been rewritten to support creating projects from custom repository URLs via a new \--repo\ flag and interactive template selection. It now includes a \--nomod\ flag that allows adding new services to an existing Go module, correctly calculating import paths relative to the module root. The command also respects a \--timeout\ flag to control context deadlines during project creation.
cmd/kratos/internal/project · high confidence
Behavioural changes
Introduce generic Codec interface and registration API
The encoding package now exposes a \Codec\ interface with \Marshal\, \Unmarshal\, and \Name\ methods, replacing previous reflection-based implementations. Users can register custom codecs via \RegisterCodec\ and retrieve them by content subtype using \GetCodec\. The interface uses Go's generic \any\ type for data handling, and registration validates that codecs are not nil and have a non-empty name, panicking otherwise. A README also documents the msgpack codec availability.
encoding · high confidence
Logging subsystem rewritten to use Go's standard log/slog
The logging package has been replaced with a new implementation based on Go's standard \log/slog\ library. This change introduces a new builder API (\log.NewHandler\, \log.NewLogger\) for configuring handlers with options like format (text/JSON), level, and source reporting. It adds support for context-aware attributes via \ContextWithAttrs\ and \WithExtractor\, allowing automatic injection of request-scoped data. A new filtering system (\WithFilter\, \FilterKey\, \FilterFunc\) enables redacting sensitive keys (e.g., passwords) and dropping specific log records. Package-level helpers (\Info\, \Error\, etc.) now mirror \slog\ signatures, and a \LevelFatal\ constant is added. Existing code using the old logger interface will need to migrate to the new \slog\-based API.
log · high confidence
Migrated validation library from PGV to protovalidate
The project has replaced the Protocol Buffers Validator (PGV) library with protovalidate. This change updates the underlying validation schema and implementation, meaning validation rules defined in protobuf messages now rely on the new protovalidate definitions rather than the previous PGV ones.
_third\party/buf · high confidence
Nacos registry upgraded to SDK v2 with new configuration options
The Nacos registry implementation has been migrated from the v1 to the v2 \nacos-sdk-go\ client, requiring users to update their client initialization code to use the v2 API. This update introduces two new configuration options: \WithDefaultKind\ to set a fallback service kind for discovery and \WithWeight\ to define a default instance weight. The registry now also supports reading instance weight from service metadata and uses \maps.Clone\ for safer metadata handling. Additionally, the watcher implementation has been refined to properly unsubscribe when stopped, and the codebase now includes comprehensive unit tests using a fake in-memory client.
contrib/registry/nacos · high confidence
Refactored CLI base utilities for Go module and repository management
The \cmd/kratos/internal/base\ package has been rewritten to modernize how the Kratos CLI handles Go modules and Git repositories. New \install.go\ and \mod.go\ files provide utilities for installing Go tools via \go install\ and parsing \go.mod\ files, including a \KratosMod\ function that resolves the local Kratos v3 installation path using the \GOMODCACHE\ environment variable. The \repo.go\ file introduces a \Repo\ struct that manages cloning and pulling Git repositories with branch support, while \vcs\_url.go\ adds robust parsing for various Git URL formats, including SCP-style syntax. Supporting changes in \path.go\ update file copying and directory tree printing to use modern Go APIs, and new test files (\mod\_test.go\, \repo\_test.go\, \vcs\_url\_test.go\) verify these behaviors.
cmd/kratos/internal/base · high confidence
Registry module introduces v3 interfaces and ServiceInstance equality check
The registry module has been updated to v3, introducing new \Registrar\, \Discovery\, and \Watcher\ interfaces in \registry.go\ that define the core service registration and discovery contracts. The \ServiceInstance\ struct is now part of this core module and includes a new \Equal\ method, allowing users to reliably compare service instances by checking ID, name, version, endpoints, and metadata. Documentation in \README.md\ has been added to guide users on installing the corresponding v3 registry implementations for Consul, Etcd, Zookeeper, Nacos, Kubernetes, and Polaris from the \contrib\ directory.
registry · high confidence
Validate middleware now uses protovalidate with legacy PGV compatibility
The validation middleware in contrib/middleware/validate has migrated from the legacy protoc-gen-validate (PGV) to protovalidate. For most users, existing code remains unchanged because the middleware retains compatibility with the old PGV-generated validation functions (the legacy mode). However, users who have manually implemented the Validator interface must migrate their implementations to work with the new protovalidate-based middleware.
contrib/middleware/validate · high confidence
Zookeeper registry implementation with auto-re-registration and ACL support
The Zookeeper registry in contrib/registry/zookeeper has been rewritten to improve reliability and security. It now automatically re-registers ephemeral service nodes after connection restarts or session timeouts, preventing service discovery failures. The implementation also adds support for Zookeeper Digest ACLs via the new WithDigestACL option, allowing authenticated service registration. Additionally, the watcher logic has been hardened to handle missing nodes gracefully by setting existence watchers when a service path does not yet exist.
contrib/registry/zookeeper · high confidence
Fixes
Added protobuf test data for google.protobuf.Struct support
Added \test.proto\ and its generated Go code (\test.pb.go\) to the internal encoding test data, introducing \StructPb\ messages that utilize \google.protobuf.Struct\ and \google.protobuf.Struct\ lists. This test fixture supports the fix for parsing query parameters containing \google.protobuf.Struct\ types, which previously failed with an unsupported message type error.
internal/testdata/encoding · high confidence
Test coverage
Add binding test data with field mask and optional fields; Added complex protobuf test data for encoding validation.
Dependencies
Upgrade to Kratos v3 and Go 1.25
The Kratos framework and its CLI tools have been upgraded to version 3, with the Go toolchain requirement raised to 1.25. This major version update includes updated dependencies for core components such as the CLI (\cmd/kratos\), the error code generator (\protoc-gen-go-errors\), and the HTTP code generator (\protoc-gen-go-http\). Contributed modules, including configuration providers for Apollo and Consul, have also been migrated to the v3 module path and updated to align with the new framework version.
(dependencies) · high confidence
Written by cca.canine.dev from the codebase's own history, inside the signed delivery this page is composed from.
How this codebase got here
This is the PUBLIC form of this artifact. Findings are listed in full, but the details of SECURITY findings — which rule fired, in which file, on which line, and how to fix it — are deliberately withheld, and any secret-scanner results are excluded entirely. Where detail is absent here it was REMOVED FOR PUBLICATION; it is not missing from the analysis. The complete artifact is available from the repository owner.
Score
- CAI 57 → 58 (+0.6)
- Rubric changed (rubric-2026.10.5 → rubric-2026.11.3) — scores are not directly comparable.
Lenses
- Code Health 82 → 82 (-0.0)
- Architecture 68 → 68 (-0.2)
- Maturity 51 → 58 (+7.6)
- Readiness 64 → 63 (-1.0)
- Security 55 → 50 (-5.2)
- Performance 85 → 95 (+10.3)
Resolved (13)
- Disclosure policy has no reporting contact
- Documentation: no project overview (contrib/registry/nacos/README.md)
- Documentation: no project overview (contrib/registry/servicecomb/README.md)
- Documentation: no project overview (third_party/buf/validate/README.md)
- Duplicated block (14 lines × 2) (transport/grpc/server.go)
- Duplicated block (8–9 lines × 2) (transport/http/stream.go)
- High: security finding (details withheld)
- High: security finding (details withheld)
- No ADRs found
- Off-boarding risk: anonymized user #1
- Rotate the exposed credentials — git history can't be un-committed
- Secret: password-hash-credential (examples/config/apollo/docker-quick-start/sql/apolloportaldb.sql)
- Secret: private-key (examples/tls/cert/server.key)
New (44)
- Disclosure policy has no reporting contact (SECURITY.md)
- Duplicated block (12–13 lines × 2) (transport/http/client.go)
- Duplicated block (14 lines × 2) (transport/grpc/server.go)
- Duplicated block (8–9 lines × 2) (transport/http/stream.go)
- Edited copies of one member (3 members, 6+ corresponding lines) (contrib/registry/consul/registry.go)
- Edited copy of a member (10 corresponding lines) (cmd/kratos/internal/base/repo.go)
- Edited copy of a member (10 corresponding lines) (contrib/registry/kubernetes/registry.go)
- Edited copy of a member (11 corresponding lines) (config/value.go)
- Edited copy of a member (12 corresponding lines) (internal/context/context.go)
- Edited copy of a member (12 corresponding lines) (log/log.go)
- Edited copy of a member (13 corresponding lines) (config/value.go)
- Edited copy of a member (13 corresponding lines) (contrib/config/kubernetes/config.go)
- Edited copy of a member (13 corresponding lines) (transport/http/stream.go)
- Edited copy of a member (14 corresponding lines) (contrib/otel/tracing/tracing.go)
- Edited copy of a member (15 corresponding lines) (contrib/registry/eureka/register.go)
- Edited copy of a member (15 corresponding lines) (encoding/form/proto_decode.go)
- Edited copy of a member (15 corresponding lines) (internal/circuitbreaker/sre.go)
- Edited copy of a member (15 corresponding lines) (internal/circuitbreaker/sre.go)
- Edited copy of a member (17 corresponding lines) (contrib/middleware/validate/validate.go)
- Edited copy of a member (18 corresponding lines) (contrib/polaris/registry.go)
- …and 24 more
Changes since last survey
- 4 commits — 4 feature/other, 0 fixes
By area
- .github/workflows — 4 commits
Notable commits
- change: build(deps): bump actions/cache from 5 to 6 (#3848)
- change: build(deps): bump actions/checkout from 6 to 7 (#3849)
- change: build(deps): bump actions/setup-go from 6 to 7 (#3862)
- change: build(deps): bump github/codeql-action from 4 to 4.37.3 (#3863)
Written by cca.canine.dev from the codebase's own history, inside the signed delivery this page is composed from.
Survey your own repository
go-kratos/kratos 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 13 November 2026 at a pinned commit. It is not a live figure and does not change until the project is measured again.
- Measured at commit dd0fb7df1e325daf5ffb9c30862be8f1091763eb — the exact code this score is about.
- Scored under rubric-2026.11.3 — the same rubric and the same method as every other entry in this index.
- Measured by Canine Code Analyzer (cca.canine.dev) using cca measure-2026.11.61+preprod-f3449e6eb431.