Documentation
¶
Index ¶
- Constants
- Variables
- func GetAs[T any](c *Config, key string, defaultValue ...T) T
- func GetAsWithError[T any](cfg *Config, key string) (T, error)
- func GetConfigErrorType(err error) string
- func GetErrorSuggestion(err error) string
- func GetSliceAs[T any](c *Config, key string) []T
- func GetWithFallback[T any](c *Config, keys ...string) T
- func IsConfigError(err error) bool
- func MustGetAs[T any](c *Config, key string) T
- func PrintErrorHelp(err error)
- func Register(module, key string, value any) error
- func ResetGlobalMetrics()
- func WorkPath(parts ...string) string
- type Config
- func (c *Config) AddValidateFunc(fn func(config map[string]any) error)
- func (c *Config) AddValidator(validator ConfigValidator)
- func (c *Config) AllSettings() map[string]any
- func (c *Config) ClearValidators()
- func (c *Config) Close() error
- func (c *Config) Get(key string, def ...any) any
- func (c *Config) GetBool(parts ...string) bool
- func (c *Config) GetBoolSlice(key string) []bool
- func (c *Config) GetCryptoType() string
- func (c *Config) GetDuration(key string) time.Duration
- func (c *Config) GetEncryptionKey() string
- func (c *Config) GetFloat(parts ...string) float64
- func (c *Config) GetFloatSlice(key string) []float64
- func (c *Config) GetInt(parts ...string) int
- func (c *Config) GetIntSlice(key string) []int
- func (c *Config) GetMetrics() MetricsSnapshot
- func (c *Config) GetString(parts ...string) string
- func (c *Config) GetStringMap(key string) map[string]any
- func (c *Config) GetStringMapString(key string) map[string]string
- func (c *Config) GetStringSlice(key string) []string
- func (c *Config) GetTime(key string) time.Time
- func (c *Config) GetValidators() []ConfigValidator
- func (c *Config) GetWithError(key string) (any, error)
- func (c *Config) IsEncryptionEnabled() bool
- func (c *Config) IsSet(key string) bool
- func (c *Config) Keys() []string
- func (c *Config) Marshal(value any, prefix ...string) error
- func (c *Config) ResetMetrics()
- func (c *Config) Set(key string, value any) error
- func (c *Config) SetEnvPrefix(prefix string) error
- func (c *Config) Unmarshal(obj any, key ...string) error
- func (c *Config) Viper() *viper.Viper
- func (c *Config) Watch(callbacks ...func())
- func (c *Config) WatchWithContext(ctx context.Context, callbacks ...func()) context.CancelFunc
- type ConfigCrypto
- type ConfigError
- type ConfigValidateFunc
- type ConfigValidator
- type CryptoOptions
- type DefaultCrypto
- type EnvOptions
- type ErrorRecovery
- type Logger
- type Metrics
- type MetricsSnapshot
- type NopLogger
- func (l *NopLogger) Debug(args ...interface{})
- func (l *NopLogger) Debugf(format string, args ...interface{})
- func (l *NopLogger) Error(args ...interface{})
- func (l *NopLogger) Errorf(format string, args ...interface{})
- func (l *NopLogger) Fatal(args ...interface{})
- func (l *NopLogger) Fatalf(format string, args ...interface{})
- func (l *NopLogger) Info(args ...interface{})
- func (l *NopLogger) Infof(format string, args ...interface{})
- func (l *NopLogger) Warn(args ...interface{})
- func (l *NopLogger) Warnf(format string, args ...interface{})
- type Option
- func WithBindPFlags(flags ...*pflag.FlagSet) Option
- func WithCacheTiming(warmup, rebuild time.Duration) Option
- func WithContent(content string) Option
- func WithCrypto(opts CryptoOptions) Option
- func WithEncryption(key string) Option
- func WithEncryptionCrypto(crypto ConfigCrypto) Option
- func WithEnv(prefix string) Option
- func WithEnvOptions(opts EnvOptions) Option
- func WithEnvSmartCase(prefix string, smartCase bool) Option
- func WithLogger(logger Logger) Option
- func WithMode(mode string) Option
- func WithName(name string) Option
- func WithPath(path string) Option
- func WithValidateFunc(fn func(config map[string]any) error) Option
- func WithValidator(validator ConfigValidator) Option
- func WithValidators(validators ...ConfigValidator) Option
- func WithWriteFlushDelay(delay time.Duration) Option
- type ParamParser
- type PerformanceMonitor
Constants ¶
const ( ErrTypeFileNotFound = "FileNotFound" ErrTypePermission = "Permission" ErrTypeInvalidFormat = "InvalidFormat" ErrTypeValidation = "Validation" ErrTypeDecryption = "Decryption" ErrTypeConversion = "Conversion" ErrTypeEnvironment = "Environment" ErrTypeInitialization = "Initialization" )
错误类型常量
Variables ¶
Functions ¶
func GetAs ¶ added in v0.2.0
GetAs 泛型获取配置值,提供类型安全的访问方式 支持类型: string, int, int32, int64, float32, float64, bool, time.Duration, time.Time
使用示例:
host := cfg.GetAs[string]("database.host", "localhost")
port := cfg.GetAs[int]("database.port", 5432)
timeout := cfg.GetAs[time.Duration]("timeout", 30*time.Second)
func GetAsWithError ¶ added in v1.0.6
GetAsWithError 返回转换后的值和错误,便于区分键不存在或转换失败的具体原因
func GetConfigErrorType ¶ added in v0.2.0
GetConfigErrorType 获取配置错误类型
func GetErrorSuggestion ¶ added in v0.2.0
GetErrorSuggestion 根据错误类型提供修复建议
func GetSliceAs ¶ added in v0.2.0
GetSliceAs 泛型获取切片配置值 支持类型: []string, []int, []float64, []bool
使用示例:
features := cfg.GetSliceAs[string]("server.features")
ports := cfg.GetSliceAs[int]("server.ports")
func GetWithFallback ¶ added in v0.2.0
GetWithFallback 获取配置值,支持多个fallback键 按顺序尝试每个键,直到找到有效值
使用示例:
port := cfg.GetWithFallback[int]("server.port", "app.port", "port")
Types ¶
type Config ¶
type Config struct {
// contains filtered or unexported fields
}
Config 统一配置实现
func (*Config) AddValidateFunc ¶ added in v0.2.0
AddValidateFunc 添加配置验证函数(便利方法)
func (*Config) AddValidator ¶ added in v0.2.0
func (c *Config) AddValidator(validator ConfigValidator)
AddValidator 添加配置验证器
func (*Config) AllSettings ¶ added in v0.2.0
AllSettings 获取所有配置(返回副本以保证线程安全)
func (*Config) ClearValidators ¶ added in v0.2.0
func (c *Config) ClearValidators()
ClearValidators 清除所有验证器
func (*Config) GetBool ¶
GetBool 获取布尔值配置
支持两种调用方式:
- GetBool("database.host", "true") - 点号分隔的键名
- GetBool("database", "host", "true") - 多参数形式
参数:
- parts: 可变参数,最后一个参数可选作为默认值
返回值:
- 布尔类型的配置值,如果键不存在且提供了默认值则返回默认值
func (*Config) GetCryptoType ¶ added in v0.2.0
GetCryptoType 获取当前使用的加密类型
func (*Config) GetEncryptionKey ¶ added in v0.2.0
GetEncryptionKey 获取当前使用的加密密钥(如果适用)
func (*Config) GetFloat ¶
GetFloat 获取浮点数配置
支持两种调用方式:
- GetFloat("metrics.value", "0.95") - 点号分隔的键名
- GetFloat("metrics", "value", "0.95") - 多参数形式
参数:
- parts: 可变参数,最后一个参数可选作为默认值
返回值:
- 浮点类型的配置值,如果键不存在且提供了默认值则返回默认值
func (*Config) GetFloatSlice ¶ added in v0.2.0
GetFloatSlice 获取浮点数切片配置
参数:
- key: 配置键名
返回值:
- 浮点数切片类型的配置值
func (*Config) GetInt ¶
GetInt 获取整数配置
支持两种调用方式:
- GetInt("database.port", "5432") - 点号分隔的键名
- GetInt("database", "port", "5432") - 多参数形式
参数:
- parts: 可变参数,最后一个参数可选作为默认值
返回值:
- 整数类型的配置值,如果键不存在且提供了默认值则返回默认值
func (*Config) GetMetrics ¶ added in v0.2.0
func (c *Config) GetMetrics() MetricsSnapshot
GetMetrics 获取配置的性能指标(使用全局监控器)
func (*Config) GetString ¶
GetString 获取字符串配置
支持两种调用方式:
- GetString("database.host", "localhost") - 点号分隔的键名
- GetString("database", "host", "localhost") - 多参数形式
参数:
- parts: 可变参数,最后一个参数可选作为默认值
返回值:
- 字符串类型的配置值,如果键不存在且提供了默认值则返回默认值
func (*Config) GetStringMapString ¶ added in v0.1.1
GetStringMapString 获取字符串-字符串映射配置
参数:
- key: 配置键名
返回值:
- 字符串到字符串的映射类型配置值
func (*Config) GetValidators ¶ added in v0.2.0
func (c *Config) GetValidators() []ConfigValidator
GetValidators 获取当前所有验证器(只读)
func (*Config) GetWithError ¶ added in v0.2.0
GetWithError 获取配置值并返回错误信息
参数:
- key: 配置键名
返回值:
- 配置值和可能的错误
func (*Config) IsEncryptionEnabled ¶ added in v0.2.0
IsEncryptionEnabled 检查是否启用了加密
func (*Config) Marshal ¶ added in v0.1.7
Marshal 将结构体或其他数据类型序列化并保存到配置中
参数:
- value: 要序列化的值(通常是结构体)
- prefix: 可选的配置键前缀,用于指定保存路径
返回值:
- error: 序列化过程中遇到的错误,成功则为nil
func (*Config) ResetMetrics ¶ added in v0.2.0
func (c *Config) ResetMetrics()
ResetMetrics 重置性能指标(使用全局监控器)
func (*Config) SetEnvPrefix ¶ added in v0.1.1
validateAllConfigsWithData 使用传入数据执行全量验证,避免重复持锁。 SetEnvPrefix 更新环境变量选项
func (*Config) Unmarshal ¶
Unmarshal 将配置解析到结构体 key 为空时解析整个配置,否则解析指定的配置段 支持 default 标签设置默认值 支持 required 标签验证必填字段 支持大驼峰命名风格的结构体字段自动映射到下划线风格的配置键名
func (*Config) WatchWithContext ¶ added in v0.2.0
func (c *Config) WatchWithContext(ctx context.Context, callbacks ...func()) context.CancelFunc
WatchWithContext 监听配置变化并返回取消函数,用于显式停止监听。
type ConfigCrypto ¶ added in v0.2.0
type ConfigCrypto interface {
// Encrypt 加密配置数据
// data: 要加密的配置数据(通常是YAML/JSON等格式的字节数组)
// 返回: 加密后的数据和错误
Encrypt(data []byte) ([]byte, error)
// Decrypt 解密配置数据
// data: 要解密的数据
// 返回: 解密后的原始配置数据和错误
Decrypt(data []byte) ([]byte, error)
// IsEncrypted 检查数据是否已加密
// data: 要检查的数据
// 返回: 如果数据已加密返回true,否则返回false
IsEncrypted(data []byte) bool
}
ConfigCrypto 配置加密接口 用户可以实现此接口来提供自定义的加密算法
func NewCrypto ¶ added in v0.2.0
func NewCrypto(key string) (ConfigCrypto, error)
NewCrypto 创建默认加密器的便利函数(向后兼容)
type ConfigError ¶ added in v0.2.0
type ConfigError struct {
Type string `json:"type"`
Message string `json:"message"`
Key string `json:"key,omitempty"`
Value string `json:"value,omitempty"`
File string `json:"file,omitempty"`
Cause error `json:"-"`
}
ConfigError 配置错误类型
func NewConfigError ¶ added in v0.2.0
func NewConfigError(errorType, message string) *ConfigError
NewConfigError 创建新的配置错误
func NewConfigErrorWithCause ¶ added in v0.2.0
func NewConfigErrorWithCause(errorType, message string, cause error) *ConfigError
NewConfigErrorWithCause 创建带原因的配置错误
func NewConfigErrorWithDetails ¶ added in v0.2.0
func NewConfigErrorWithDetails(errorType, message, key, value, file string, cause error) *ConfigError
NewConfigErrorWithDetails 创建带详细信息的配置错误
func (*ConfigError) Error ¶ added in v0.2.0
func (e *ConfigError) Error() string
func (*ConfigError) Unwrap ¶ added in v0.2.0
func (e *ConfigError) Unwrap() error
type ConfigValidateFunc ¶ added in v0.2.0
配置验证函数类型(用于简化接口实现)
func (ConfigValidateFunc) GetName ¶ added in v0.2.0
func (f ConfigValidateFunc) GetName() string
GetName 实现ConfigValidator接口
type ConfigValidator ¶ added in v0.2.0
type ConfigValidator interface {
// Validate 验证配置
// config: 当前所有配置的map形式
// 返回: 验证错误,如果验证通过则返回nil
Validate(config map[string]any) error
// GetName 获取验证器名称
GetName() string
}
配置验证器接口
type CryptoOptions ¶ added in v0.2.0
type CryptoOptions struct {
Enabled bool // 是否启用加密
Crypto ConfigCrypto // 加密实现,如果为nil则使用默认ChaCha20加密
Key string // 加密密钥,如果为空则生成随机密钥
}
CryptoOptions 加密配置选项
type DefaultCrypto ¶ added in v0.2.0
type DefaultCrypto struct {
// contains filtered or unexported fields
}
DefaultCrypto 默认加密实现 - 使用 ChaCha20-Poly1305
ChaCha20-Poly1305 的优势: - 高性能:在各种硬件平台上都有优秀的性能表现 - 现代密码学:被广泛认可的现代AEAD算法 - 安全性:提供认证加密,同时保证机密性和完整性 - 抗侧信道攻击:相比AES在软件实现中更安全 - 移动友好:在ARM处理器上性能特别出色
func NewChaCha20Crypto ¶ added in v0.2.0
func NewChaCha20Crypto(key string) (*DefaultCrypto, error)
NewChaCha20Crypto 别名函数,指向默认加密器
func NewChaCha20CryptoFromKey ¶ added in v0.2.0
func NewChaCha20CryptoFromKey(encodedKey string) (*DefaultCrypto, error)
NewChaCha20CryptoFromKey 别名函数,指向默认加密器
func NewDefaultCrypto ¶ added in v0.2.0
func NewDefaultCrypto(key string) (*DefaultCrypto, error)
NewDefaultCrypto 创建新的默认加密器 key: 加密密钥,如果为空则生成随机密钥
func NewDefaultCryptoFromKey ¶ added in v0.2.0
func NewDefaultCryptoFromKey(encodedKey string) (*DefaultCrypto, error)
NewDefaultCryptoFromKey 从base64编码的密钥创建默认加密器
func (*DefaultCrypto) Decrypt ¶ added in v0.2.0
func (d *DefaultCrypto) Decrypt(data []byte) ([]byte, error)
Decrypt 实现ConfigCrypto接口的解密方法
func (*DefaultCrypto) Encrypt ¶ added in v0.2.0
func (d *DefaultCrypto) Encrypt(data []byte) ([]byte, error)
Encrypt 实现ConfigCrypto接口的加密方法
func (*DefaultCrypto) GetKey ¶ added in v0.2.0
func (d *DefaultCrypto) GetKey() string
GetKey 获取加密密钥的base64编码(用于保存和恢复)
func (*DefaultCrypto) GetKeyBytes ¶ added in v0.2.0
func (d *DefaultCrypto) GetKeyBytes() []byte
GetKeyBytes 获取原始密钥字节(用于高级用途)
func (*DefaultCrypto) IsEncrypted ¶ added in v0.2.0
func (d *DefaultCrypto) IsEncrypted(data []byte) bool
IsEncrypted 检查数据是否已加密
type EnvOptions ¶
type EnvOptions struct {
Prefix string // 环境变量前缀
Enabled bool // 是否启用环境变量
SmartCase bool // 支持多种大小写格式的环境变量
}
EnvOptions 环境变量配置选项
type ErrorRecovery ¶ added in v0.2.0
type ErrorRecovery struct {
// contains filtered or unexported fields
}
ErrorRecovery 错误恢复策略
func NewErrorRecovery ¶ added in v0.2.0
func NewErrorRecovery(config *Config) *ErrorRecovery
NewErrorRecovery 创建错误恢复实例
func (*ErrorRecovery) RecoverFromError ¶ added in v0.2.0
func (er *ErrorRecovery) RecoverFromError(err error) error
RecoverFromError 从错误中恢复
type Logger ¶ added in v0.1.8
type Logger interface {
// Debug 记录调试级别的日志
Debug(args ...interface{})
// Debugf 格式化记录调试级别的日志
Debugf(format string, args ...interface{})
// Info 记录信息级别的日志
Info(args ...interface{})
// Infof 格式化记录信息级别的日志
Infof(format string, args ...interface{})
// Warn 记录警告级别的日志
Warn(args ...interface{})
// Warnf 格式化记录警告级别的日志
Warnf(format string, args ...interface{})
// Error 记录错误级别的日志
Error(args ...interface{})
// Errorf 格式化记录错误级别的日志
Errorf(format string, args ...interface{})
// Fatal 记录致命错误级别的日志
Fatal(args ...interface{})
// Fatalf 格式化记录致命错误级别的日志
Fatalf(format string, args ...interface{})
}
Logger 日志接口定义,用于配置系统中的日志记录
type Metrics ¶ added in v0.2.0
type Metrics struct {
StartTime time.Time `json:"start_time"`
GetCount int64 `json:"get_count"`
SetCount int64 `json:"set_count"`
CacheHits int64 `json:"cache_hits"`
CacheMisses int64 `json:"cache_misses"`
LastGetTime time.Time `json:"last_get_time"`
LastSetTime time.Time `json:"last_set_time"`
ErrorCount int64 `json:"error_count"`
OperationTimes map[string]time.Duration `json:"operation_times"`
// contains filtered or unexported fields
}
Metrics 配置性能指标
func (*Metrics) GetStats ¶ added in v0.2.0
func (m *Metrics) GetStats() MetricsSnapshot
GetStats 获取统计信息
func (*Metrics) RecordOperation ¶ added in v0.2.0
RecordOperation 记录自定义操作时间
type MetricsSnapshot ¶ added in v0.2.0
type MetricsSnapshot struct {
StartTime time.Time `json:"start_time"`
Uptime time.Duration `json:"uptime"`
GetCount int64 `json:"get_count"`
SetCount int64 `json:"set_count"`
CacheHits int64 `json:"cache_hits"`
CacheMisses int64 `json:"cache_misses"`
CacheHitRatio float64 `json:"cache_hit_ratio"`
ErrorCount int64 `json:"error_count"`
AvgGetTime time.Duration `json:"avg_get_time"`
AvgSetTime time.Duration `json:"avg_set_time"`
LastGetTime time.Time `json:"last_get_time"`
LastSetTime time.Time `json:"last_set_time"`
OperationTimes map[string]time.Duration `json:"operation_times"`
}
MetricsSnapshot 性能指标快照
func GetGlobalMetrics ¶ added in v0.2.0
func GetGlobalMetrics() MetricsSnapshot
GetGlobalMetrics 获取全局性能指标
func (MetricsSnapshot) GetSummary ¶ added in v0.2.0
func (s MetricsSnapshot) GetSummary() string
GetSummary 获取性能摘要字符串
type NopLogger ¶ added in v0.1.8
type NopLogger struct{}
NopLogger 空日志实现,不执行任何操作
func (*NopLogger) Debug ¶ added in v0.1.8
func (l *NopLogger) Debug(args ...interface{})
Debug 实现Logger接口
func (*NopLogger) Error ¶ added in v0.1.8
func (l *NopLogger) Error(args ...interface{})
Error 实现Logger接口
func (*NopLogger) Fatal ¶ added in v0.1.8
func (l *NopLogger) Fatal(args ...interface{})
Fatal 实现Logger接口
func (*NopLogger) Info ¶ added in v0.1.8
func (l *NopLogger) Info(args ...interface{})
Info 实现Logger接口
type Option ¶
type Option func(*Config)
Option 配置选项
func WithBindPFlags ¶ added in v0.1.7
WithBindPFlags 设置命令行标志绑定
func WithCacheTiming ¶ added in v0.2.0
WithCacheTiming 设置读取缓存的预热与重建延迟。 传入 0 或负值可用于禁用对应延迟并在同一 goroutine 中立即刷新。
func WithEncryption ¶ added in v0.2.0
WithEncryption 便利函数:启用配置加密并设置密钥 key: 加密密钥,如果为空则生成随机密钥
func WithEncryptionCrypto ¶ added in v0.2.0
func WithEncryptionCrypto(crypto ConfigCrypto) Option
WithEncryptionCrypto 便利函数:启用配置加密并使用自定义加密器 crypto: 自定义加密实现
func WithEnvSmartCase ¶ added in v0.2.0
WithEnvSmartCase 便利函数:设置环境变量选项并明确指定智能大小写匹配
func WithValidateFunc ¶ added in v0.2.0
WithValidateFunc 添加配置验证函数(便利方法)
func WithValidator ¶ added in v0.2.0
func WithValidator(validator ConfigValidator) Option
WithValidator 添加配置验证器
func WithValidators ¶ added in v0.2.0
func WithValidators(validators ...ConfigValidator) Option
WithValidators 批量添加多个验证器
func WithWriteFlushDelay ¶ added in v0.2.0
WithWriteFlushDelay 设置配置写入的延迟时间,为0或负值时表示立即写入。
type ParamParser ¶ added in v0.2.0
type ParamParser struct{}
ParamParser 参数解析器
func (*ParamParser) ParseKeyAndDefault ¶ added in v0.2.0
func (p *ParamParser) ParseKeyAndDefault(parts []string) (string, string, bool)
ParseKeyAndDefault 解析配置键和默认值 返回: (key, defaultValue, hasDefault)
type PerformanceMonitor ¶ added in v0.2.0
type PerformanceMonitor struct {
// contains filtered or unexported fields
}
PerformanceMonitor 性能监控器
func NewPerformanceMonitor ¶ added in v0.2.0
func NewPerformanceMonitor(config *Config, interval time.Duration) *PerformanceMonitor
NewPerformanceMonitor 创建性能监控器
func (*PerformanceMonitor) Start ¶ added in v0.2.0
func (pm *PerformanceMonitor) Start()
Start 启动性能监控
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
examples
|
|
|
cmd/demo_basic
command
|
|
|
cmd/demo_hotreload
command
|
|
|
cmd/demo_hotreload_encrypted
command
|
|
|
cmd/encryption_demo
command
|
|
|
cmd/memory_and_validation
command
|
|
|
cmd/smart_case
command
|
|
|
cmd/validation_integration
command
|
|
|
internal
|
|