Documentation
¶
Overview ¶
Application scenarios: - Define the cache contract used by business services and framework providers. - Standardize cache read, write, delete, and remember-style loading semantics. - Expose shared cache constants and sentinel errors across implementations.
适用场景: - 定义业务服务和框架 provider 共同使用的缓存契约。 - 统一缓存读取、写入、删除和 remember 风格加载语义。 - 在不同实现之间共享缓存常量与哨兵错误。
Application scenarios: - Define the configuration contracts used by config providers and business code. - Standardize config loading, watching, reloading, and typed reads. - Provide a shared model for external config source selection and connection settings.
适用场景: - 定义配置 provider 和业务代码共同依赖的配置契约。 - 统一配置加载、监听、重载和类型化读取语义。 - 为外部配置源选择和连接参数提供共享模型。
Application scenarios: - Define the distributed lock contract shared by lock providers and business code. - Standardize lock acquisition, renewal, release, and guarded execution semantics. - Provide a common config model for choosing lock backends and retry behavior.
适用场景: - 定义分布式锁 provider 和业务代码共同依赖的锁契约。 - 统一加锁、续租、解锁和受保护执行语义。 - 为锁后端选择和重试行为提供通用配置模型。
Application scenarios: - Define lightweight schema inspection contracts for databases used by the framework. - Expose table and column metadata in a backend-neutral way. - Support health checks and schema introspection tooling without binding to one ORM.
适用场景: - 定义框架使用的轻量数据库结构探查契约。 - 以与后端无关的方式暴露表和列元数据。 - 在不绑定单一 ORM 的情况下支持健康检查和结构探查工具。
Application scenarios: - Define shared database and ORM contracts used by runtime providers. - Standardize backend selection keys and minimal database execution capabilities. - Keep Gorm, SQLX, and Ent integrations behind stable framework-level contracts.
适用场景: - 定义运行时 provider 使用的共享数据库与 ORM 契约。 - 统一后端选择键和最小数据库执行能力。 - 让 Gorm、SQLX 和 Ent 集成稳定地收敛在框架级契约之后。
Application scenarios: - Define the Redis contract used by providers and business helpers. - Standardize basic Redis key-value semantics without exposing a concrete client type. - Share Redis-related constants across integrations and middleware.
适用场景: - 定义 provider 和业务辅助代码共同使用的 Redis 契约。 - 在不暴露具体客户端类型的前提下统一基础 Redis 键值语义。 - 在集成和中间件之间共享 Redis 相关常量。
Application scenarios: - Define the validation contract shared by validation providers and HTTP middleware. - Standardize object validation, locale switching, custom rule registration, and error translation. - Provide reusable models for validation errors and validation-specific config.
适用场景: - 定义校验 provider 和 HTTP 中间件共同依赖的校验契约。 - 统一对象校验、语言切换、自定义规则注册和错误翻译语义。 - 为校验错误和校验专用配置提供可复用的数据模型。
Index ¶
- Constants
- Variables
- func IsRedisNil(err error) bool
- type BinaryCache
- type Cache
- type Column
- type Config
- type ConfigSource
- type ConfigSourceConfig
- type ConfigSourceType
- type ConfigWatcher
- type CustomRuleConfig
- type CustomValidateFunc
- type DBConfig
- type DBInspector
- type DistributedLock
- type DistributedLockConfig
- type EntClientFactory
- type GormDB
- type Migrator
- type Redis
- type RuntimeBackend
- type SQLExecutor
- type SQLX
- type Table
- type ValidationError
- type ValidationErrors
- type Validator
- type ValidatorConfig
Constants ¶
const ( GormKey = "framework.orm.gorm" SQLXKey = "framework.orm.sqlx" ORMBackendKey = "framework.orm.backend" DBRuntimeKey = "framework.orm.runtime" EntClientKey = "framework.orm.ent" EntClientFactoryKey = "framework.orm.ent.factory" MigratorKey = "framework.orm.migrator" SQLExecutorKey = "framework.orm.sql_executor" )
const BinaryCacheKey = "framework.binary_cache"
BinaryCacheKey is the container key for the binary cache capability.
BinaryCacheKey 是二进制缓存能力的容器键。
const CacheKey = "framework.cache"
CacheKey is the container key for the cache capability.
CacheKey 是缓存能力的容器键。
const ConfigKey = "framework.config"
ConfigKey is the container key for the config capability.
ConfigKey 是配置能力的容器键。
const ConfigSourceKey = "framework.config.source"
ConfigSourceKey is the container key for the config source capability.
ConfigSourceKey 是配置源能力的容器键。
const ConfigWatcherKey = "framework.config.watcher"
ConfigWatcherKey is the container key for the config watcher capability.
ConfigWatcherKey 是配置监听能力的容器键。
const DBInspectorKey = "framework.orm.inspector"
DBInspectorKey is the container key for the database inspector capability.
DBInspectorKey 是数据库探查能力的容器键。
const DistributedLockKey = "framework.distributed_lock"
DistributedLockKey is the container key for the distributed lock capability.
DistributedLockKey 是分布式锁能力的容器键。
const RedisKey = "framework.redis"
RedisKey is the container key for the Redis capability.
RedisKey 是 Redis 能力的容器键。
const RedisNilString = "redis: nil"
RedisNilString is the canonical missing-value string returned by Redis clients.
RedisNilString 是 Redis 客户端返回空值时的标准字符串表示。
const ValidatorKey = "framework.validator"
ValidatorKey is the container key for the validator capability.
ValidatorKey 是校验器能力的容器键。
Variables ¶
var ErrCacheMiss = errors.New("cache miss")
ErrCacheMiss indicates that the requested cache value does not exist.
ErrCacheMiss 表示请求的缓存值不存在。
Functions ¶
func IsRedisNil ¶
IsRedisNil checks whether the given error represents a Redis nil (key not found) response. This is more robust than raw string matching and should be used instead of strings.Contains(err.Error(), RedisNilString).
IsRedisNil 检查给定错误是否为 Redis nil(键不存在)响应。 比直接字符串匹配更健壮,应优先使用。
Types ¶
type BinaryCache ¶
type BinaryCache interface {
// Get reads a cached []byte value by key.
//
// Get 按 key 读取缓存 []byte 值。
Get(ctx context.Context, key string) ([]byte, error)
// Set writes a []byte value into cache with a TTL.
//
// Set 按 TTL 将 []byte 值写入缓存。
Set(ctx context.Context, key string, value []byte, ttl time.Duration) error
// Del deletes a cached value by key.
//
// Del 按 key 删除缓存值。
Del(ctx context.Context, key string) error
// MGet reads multiple cached values in one call.
//
// MGet 一次调用读取多个缓存值。
MGet(ctx context.Context, keys ...string) (map[string][]byte, error)
// MSet writes multiple key-value pairs in one call.
//
// MSet 一次调用写入多个键值对。
MSet(ctx context.Context, kvs map[string][]byte, ttl time.Duration) error
// Remember loads from cache first and computes the value on miss.
//
// Remember 先查缓存,未命中时再计算并回填结果。
Remember(ctx context.Context, key string, ttl time.Duration, fn func(context.Context) ([]byte, error)) ([]byte, error)
}
BinaryCache defines binary-safe cache operations using []byte values. Use this interface when caching binary data (protobuf, images, etc.).
BinaryCache 定义使用 []byte 值类型的二进制安全缓存操作。 当缓存二进制数据(protobuf、图片等)时使用此接口。
type Cache ¶
type Cache interface {
// Get reads a cached string value by key.
//
// Get 按 key 读取缓存字符串值。
Get(ctx context.Context, key string) (string, error)
// Set writes a string value into cache with a TTL.
//
// Set 按 TTL 将字符串值写入缓存。
Set(ctx context.Context, key, value string, ttl time.Duration) error
// Del deletes a cached value by key.
//
// Del 按 key 删除缓存值。
Del(ctx context.Context, key string) error
// MGet reads multiple cached values in one call.
//
// MGet 一次调用读取多个缓存值。
MGet(ctx context.Context, keys ...string) (map[string]string, error)
// MSet writes multiple key-value pairs in one call.
//
// MSet 一次调用写入多个键值对。
MSet(ctx context.Context, kvs map[string]string, ttl time.Duration) error
// Remember loads from cache first and computes the value on miss.
//
// Remember 先查缓存,未命中时再计算并回填结果。
Remember(ctx context.Context, key string, ttl time.Duration, fn func(context.Context) (string, error)) (string, error)
}
Cache defines the common cache operations exposed by the framework. Uses string values for simplicity and JSON compatibility. For binary-safe caching, use BinaryCache which uses []byte values.
Cache 定义框架对外暴露的通用缓存操作。 使用 string 值类型以简化使用和 JSON 兼容。 如需二进制安全缓存,请使用 BinaryCache(使用 []byte 值类型)。
type Column ¶
type Column struct {
Name string
Type string
NotNull bool
PrimaryKey bool
DefaultVal *string
Comment string // Column comment from database schema.
}
Column describes basic database column metadata.
Column 描述数据库列的基础元数据。
type Config ¶
type Config interface {
// Env returns the current application environment name.
//
// Env 返回当前应用环境名。
Env() string
// Get reads a raw config value by key.
//
// Get 按 key 读取原始配置值。
Get(key string) any
// GetString reads a config value as string.
//
// GetString 以字符串形式读取配置值。
GetString(key string) string
// GetInt reads a config value as int.
//
// GetInt 以整数形式读取配置值。
GetInt(key string) int
// GetBool reads a config value as bool.
//
// GetBool 以布尔形式读取配置值。
GetBool(key string) bool
// GetFloat reads a config value as float64.
//
// GetFloat 以 float64 形式读取配置值。
GetFloat(key string) float64
// Unmarshal decodes a config subtree into the target object.
//
// Unmarshal 将配置子树解码到目标对象。
Unmarshal(key string, out any) error
// Watch subscribes to changes of a given config key.
//
// Watch 订阅指定配置 key 的变更事件。
Watch(ctx context.Context, key string) (ConfigWatcher, error)
// Reload forces a config refresh from the underlying source.
//
// Reload 强制从底层配置源刷新配置。
Reload(ctx context.Context) error
}
Config defines the runtime configuration view exposed by the framework.
Config 定义框架对外暴露的运行时配置视图。
type ConfigSource ¶
type ConfigSource interface {
// Load loads the full config snapshot.
//
// Load 加载完整配置快照。
Load(ctx context.Context) (map[string]any, error)
// Get reads a single config value from the source.
//
// Get 从配置源读取单个配置值。
Get(ctx context.Context, key string) (any, error)
// Set writes a config value back to the source when supported.
//
// Set 在配置源支持时回写配置值。
Set(ctx context.Context, key string, value any) error
// Watch subscribes to source-side changes of a config key.
//
// Watch 订阅配置源侧的指定 key 变更。
Watch(ctx context.Context, key string) (ConfigWatcher, error)
// Close releases resources held by the source.
//
// Close 释放配置源持有的资源。
Close() error
}
ConfigSource defines the pluggable backing source for configuration.
ConfigSource 定义可插拔的底层配置源契约。
type ConfigSourceConfig ¶
type ConfigSourceConfig struct {
Type ConfigSourceType `mapstructure:"type"`
ConsulAddr string `mapstructure:"consul_addr"`
ConsulPath string `mapstructure:"consul_path"`
ConsulToken string `mapstructure:"consul_token"`
EtcdEndpoints []string `mapstructure:"etcd_endpoints"`
EtcdPath string `mapstructure:"etcd_path"`
EtcdUsername string `mapstructure:"etcd_username"`
EtcdPassword string `mapstructure:"etcd_password"`
NacosAddr string `mapstructure:"nacos_addr"`
NacosNamespace string `mapstructure:"nacos_namespace"`
NacosGroup string `mapstructure:"nacos_group"`
NacosDataID string `mapstructure:"nacos_data_id"`
ApolloAddr string `mapstructure:"apollo_addr"`
ApolloNamespace string `mapstructure:"apollo_namespace"`
ApolloAppID string `mapstructure:"apollo_app_id"`
}
ConfigSourceConfig describes the external connection settings of a config source.
ConfigSourceConfig 描述配置源的外部连接配置。
type ConfigSourceType ¶
type ConfigSourceType string
ConfigSourceType identifies the implementation type of a config source.
ConfigSourceType 标识配置源实现类型。
const ( ConfigSourceLocal ConfigSourceType = "local" ConfigSourceConsul ConfigSourceType = "consul" ConfigSourceEtcd ConfigSourceType = "etcd" ConfigSourceNacos ConfigSourceType = "nacos" ConfigSourceApollo ConfigSourceType = "apollo" ConfigSourceNoop ConfigSourceType = "noop" )
type ConfigWatcher ¶
type ConfigWatcher interface {
// OnChange registers a callback for key changes.
//
// OnChange 为 key 变更注册回调。
OnChange(key string, callback func(value any))
// Stop stops the watcher and releases related resources.
//
// Stop 停止监听并释放相关资源。
Stop() error
}
ConfigWatcher defines the change callback contract for watched config keys.
ConfigWatcher 定义配置 key 监听后的变更回调契约。
type CustomRuleConfig ¶
type CustomRuleConfig struct {
Name string
Message string
Fn CustomValidateFunc
}
CustomRuleConfig describes one custom validation rule declaration.
CustomRuleConfig 描述单个自定义校验规则声明。
type CustomValidateFunc ¶
CustomValidateFunc defines a custom validation rule function.
CustomValidateFunc 定义自定义校验规则函数。
type DBConfig ¶
type DBConfig struct {
Driver string `mapstructure:"driver"`
Backend string `mapstructure:"backend"`
DSN string `mapstructure:"dsn"`
MaxOpenConns int `mapstructure:"max_open_conns"`
MaxIdleConns int `mapstructure:"max_idle_conns"`
// ConnMaxLifetime is the maximum amount of time a connection may be reused.
// Stored as string (e.g. "30s", "5m") for mapstructure compatibility;
// use ParseConnMaxLifetime() to convert to time.Duration.
//
// ConnMaxLifetime 是连接可复用的最长时间。
// 以字符串存储(如 "30s"、"5m")以兼容 mapstructure;
// 使用 ParseConnMaxLifetime() 转换为 time.Duration。
ConnMaxLifetime string `mapstructure:"conn_max_lifetime"`
// ConnMaxIdleTime is the maximum amount of time a connection may be idle.
// Stored as string; use ParseConnMaxIdleTime() to convert to time.Duration.
//
// ConnMaxIdleTime 是连接可空闲的最长时间。
// 以字符串存储;使用 ParseConnMaxIdleTime() 转换为 time.Duration。
ConnMaxIdleTime string `mapstructure:"conn_max_idletime"`
}
DBConfig describes database connection settings.
DBConfig 描述数据库连接配置。
func (*DBConfig) ParseConnMaxIdleTime ¶
ParseConnMaxIdleTime parses ConnMaxIdleTime string to time.Duration. Returns defaultVal if the string is empty or unparseable.
ParseConnMaxIdleTime 将 ConnMaxIdleTime 字符串解析为 time.Duration。 字符串为空或不可解析时返回 defaultVal。
func (*DBConfig) ParseConnMaxLifetime ¶
ParseConnMaxLifetime parses ConnMaxLifetime string to time.Duration. Returns defaultVal if the string is empty or unparseable.
ParseConnMaxLifetime 将 ConnMaxLifetime 字符串解析为 time.Duration。 字符串为空或不可解析时返回 defaultVal。
type DBInspector ¶
type DBInspector interface {
// Ping checks whether the database connection is available.
//
// Ping 检查数据库连接是否可用。
Ping(ctx context.Context) error
// Tables lists visible tables in the current database.
//
// Tables 列出当前数据库中可见的表。
Tables(ctx context.Context) ([]Table, error)
// Columns lists visible columns of a given table.
//
// Columns 列出指定表中可见的列。
Columns(ctx context.Context, table string) ([]Column, error)
}
DBInspector defines database inspection operations.
DBInspector 定义数据库探查操作。
type DistributedLock ¶
type DistributedLock interface {
// Lock blocks until the lock is acquired or the context is canceled.
//
// Lock 会阻塞直到成功获取锁或 context 被取消。
Lock(ctx context.Context, key string, ttl time.Duration) error
// TryLock attempts to acquire the lock immediately.
//
// TryLock 尝试立即获取锁。
TryLock(ctx context.Context, key string, ttl time.Duration) (bool, error)
// Unlock releases the lock identified by key.
//
// Unlock 释放指定 key 对应的锁。
Unlock(ctx context.Context, key string) error
// Renew extends the TTL of the lock.
//
// Renew 延长锁的 TTL。
Renew(ctx context.Context, key string, ttl time.Duration) error
// IsLocked reports whether the target key is currently locked.
//
// IsLocked 返回目标 key 当前是否处于加锁状态。
IsLocked(ctx context.Context, key string) (bool, error)
// WithLock executes the callback while holding the lock.
// Guarantees that the lock is released after fn returns (even on panic),
// using deferred unlock semantics.
//
// WithLock 在持有锁期间执行回调。
// 保证在 fn 返回后(即使 panic)自动释放锁,使用 defer unlock 语义。
WithLock(ctx context.Context, key string, ttl time.Duration, fn func() error) error
}
DistributedLock defines the distributed lock operations exposed by the framework.
DistributedLock 定义框架对外暴露的分布式锁操作。
type DistributedLockConfig ¶
type DistributedLockConfig struct {
Type string
RedisAddr string
RedisPassword string
RedisDB int
EtcdEndpoints []string
EtcdUsername string
EtcdPassword string
DefaultTTL time.Duration
RetryInterval time.Duration
MaxRetry int
KeyPrefix string
}
DistributedLockConfig describes distributed lock backend settings.
DistributedLockConfig 描述分布式锁后端配置。
type EntClientFactory ¶
type EntClientFactory interface {
// CreateEntClient creates an Ent client from the current container.
//
// CreateEntClient 从当前容器创建 Ent client。
CreateEntClient(c runtimecontract.Container) (any, error)
}
EntClientFactory defines how an Ent client should be created from the container.
EntClientFactory 定义如何从容器构建 Ent client。
type GormDB ¶
type GormDB interface {
// WithContext returns a context-bound Gorm handle.
//
// WithContext 返回绑定 context 的 Gorm 句柄。
WithContext(ctx context.Context) any
}
GormDB defines the minimal Gorm context-binding capability.
GormDB 定义最小 Gorm context 绑定能力。
type Migrator ¶
type Migrator interface {
// AutoMigrate executes schema auto migration for the given models.
//
// AutoMigrate 对给定模型执行自动迁移。
//
// ⚠ 适用范围:仅限开发/测试环境。生产环境请使用版本化迁移工具(如 golang-migrate)。
// 原因:AutoMigrate 直接 ALTER TABLE,存在丢数据、锁表风险,无法回滚,无法追踪历史。
// 开发期:改 model → 重启服务 → 表结构自动同步,快速迭代。
// 生产期:用 golang-migrate 管理版本化迁移文件,review SQL,支持 up/down。
AutoMigrate(dst ...any) error
}
Migrator defines the minimal schema migration capability.
Migrator 定义最小化的结构迁移能力。
type Redis ¶
type Redis interface {
// Ping checks whether the Redis connection is available.
//
// Ping 检查 Redis 连接是否可用。
Ping(ctx context.Context) error
// Get reads a string value by key.
//
// Get 按 key 读取字符串值。
Get(ctx context.Context, key string) (string, error)
// Set writes a string value with a TTL.
//
// Set 按 TTL 写入字符串值。
Set(ctx context.Context, key string, value string, ttl time.Duration) error
// Del deletes a key.
//
// Del 删除指定 key。
Del(ctx context.Context, key string) error
// MGet reads multiple string values in one call.
//
// MGet 一次调用读取多个字符串值。
MGet(ctx context.Context, keys ...string) (map[string]string, error)
// MSet writes multiple string values in one call.
//
// MSet 一次调用写入多个字符串值。
MSet(ctx context.Context, kvs map[string]string) error
// Expire sets a TTL on an existing key.
//
// Expire 为已存在的 key 设置 TTL。
Expire(ctx context.Context, key string, ttl time.Duration) error
}
Redis defines the minimal Redis operations exposed by the framework.
Redis 定义框架对外暴露的最小 Redis 操作集合。
type RuntimeBackend ¶
type RuntimeBackend string
RuntimeBackend identifies the database runtime backend.
RuntimeBackend 标识数据库运行时后端类型。
const ( RuntimeBackendGorm RuntimeBackend = "gorm" RuntimeBackendSQLX RuntimeBackend = "sqlx" RuntimeBackendEnt RuntimeBackend = "ent" )
func NormalizeBackendName ¶
func NormalizeBackendName(name string) RuntimeBackend
NormalizeBackendName normalizes a backend name into a supported runtime backend.
NormalizeBackendName 将后端名称归一化为受支持的运行时后端。
type SQLExecutor ¶
type SQLExecutor interface {
// ExecContext executes a SQL statement in context.
//
// ExecContext 在指定 context 中执行 SQL 语句。
ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
}
SQLExecutor defines the minimal SQL execution capability needed by the framework.
SQLExecutor 定义框架所需的最小 SQL 执行能力。
type SQLX ¶
type SQLX interface {
// SQLXExecContext executes a SQL statement through SQLX.
// Named SQLXExecContext (not ExecContext) to avoid signature conflict
// with SQLExecutor.ExecContext which returns (sql.Result, error).
//
// SQLXExecContext 通过 SQLX 执行 SQL 语句。
// 命名为 SQLXExecContext(而非 ExecContext)以避免与
// SQLExecutor.ExecContext 的返回值签名冲突。
SQLXExecContext(ctx context.Context, query string, args ...any) (any, error)
}
SQLX defines the minimal SQLX execution capability.
SQLX 定义最小 SQLX 执行能力。
type Table ¶
type Table struct {
Name string
}
Table describes a database table name.
Table 描述数据库表名。
type ValidationError ¶
ValidationError describes one field-level validation failure.
ValidationError 描述一次字段级校验失败。
type ValidationErrors ¶
type ValidationErrors []ValidationError
ValidationErrors is a collection of validation failures.
ValidationErrors 是校验失败集合。
func (ValidationErrors) Error ¶
func (e ValidationErrors) Error() string
Error returns the first validation message as the aggregate error text.
Error 返回首个校验消息作为聚合错误文本。
func (ValidationErrors) Errors ¶
func (e ValidationErrors) Errors() []string
Errors returns all validation messages as plain strings.
Errors 以纯字符串形式返回全部校验消息。
type Validator ¶
type Validator interface {
// Validate validates the target object.
//
// Validate 校验目标对象。
Validate(ctx context.Context, obj any) error
// ValidateVar validates a single value against a validation tag.
//
// ValidateVar 使用指定 tag 校验单个值。
ValidateVar(ctx context.Context, field any, tag string) error
// RegisterCustom registers a named custom validation rule.
//
// RegisterCustom 注册具名自定义校验规则。
RegisterCustom(name string, fn CustomValidateFunc) error
// SetLocale switches the active validation locale.
//
// SetLocale 切换当前校验语言环境。
SetLocale(locale string) error
// TranslateError converts a raw validation error into an app error.
// Returns an error that can be cast to resiliencecontract.AppError if needed.
//
// TranslateError 将原始校验错误转换为应用错误。
// 返回的 error 可在需要时断言为 resiliencecontract.AppError。
TranslateError(err error) error
}
Validator defines the object validation capability exposed by the framework.
Validator 定义框架对外暴露的对象校验能力。
type ValidatorConfig ¶
type ValidatorConfig struct {
Enabled bool
Locale string
TranslateErrors bool // TranslateErrors controls whether to translate validation errors.
CustomRules map[string]CustomRuleConfig
}
ValidatorConfig describes validator-level configuration.
ValidatorConfig 描述校验器级配置。