Documentation
¶
Overview ¶
Package config 提供配置管理功能,用于 enhance 框架。
该模块提供配置加载、绑定、验证、热更新等功能。 参考 Spring Boot 的配置管理体系设计。
架构设计 ¶
- Config: 配置接口,提供统一的配置访问
- Binder: 配置绑定器,支持结构体绑定
- Validator: 配置验证器接口
- WatchManager: 配置热重载管理器
- WatchEvent: 配置变更事件
- WatchCallback: 配置变更回调函数类型
- TypeConverter: 类型转换函数类型
- ValidationError: 单个验证错误
- ValidationErrors: 验证错误集合
- ValidationRule: 验证规则
核心功能 ¶
- 配置加载: 支持 JSON、YAML 等多种格式
- 配置绑定: 支持结构体自动绑定
- 配置验证: 支持配置项验证
- 热更新: 支持配置变更监听和自动刷新
- 环境变量: 支持环境变量覆盖
使用方式 ¶
加载配置:
cfg := config.NewConfig("application.json")
绑定到结构体:
type AppConfig struct {
Port int `config:"server.port"`
Name string `config:"app.name"`
}
var appCfg AppConfig
cfg.Bind(&appCfg)
监听配置变更:
cfg.Watch(func(key string, value any) {
fmt.Printf("Config changed: %s = %v\n", key, value)
})
配置优先级 ¶
配置加载优先级(从高到低):
- 命令行参数
- 环境变量
- 配置文件
- 默认值
Index ¶
- Constants
- func Bind(cfg any, target any) error
- func BindProperties(target any, env *environment.Environment, opts ...BindOption) error
- func RegisterConverter(target any, fn TypeConverter)
- func Validate(target any) error
- func Watch(key string, callback WatchCallback) error
- func WithDataID(dataID string) func(*ConfigCenterConfig)
- func WithFormat(format string) func(*ConfigCenterConfig)
- func WithGroup(group string) func(*ConfigCenterConfig)
- func WithProfiles(profiles []string) func(*ConfigCenterConfig)
- type BindOption
- type Config
- type ConfigBuilder
- func (b *ConfigBuilder) AutoEnv() *ConfigBuilder
- func (b *ConfigBuilder) Build() (*ConfigModel, error)
- func (b *ConfigBuilder) BuildAndLoad() (*ConfigModel, error)
- func (b *ConfigBuilder) EnvPrefix(prefix string) *ConfigBuilder
- func (b *ConfigBuilder) Environment(env string) *ConfigBuilder
- func (b *ConfigBuilder) File(path string) *ConfigBuilder
- func (b *ConfigBuilder) Loader(loader Loader, opts ...LoaderOption) *ConfigBuilder
- func (b *ConfigBuilder) Name(name string) *ConfigBuilder
- func (b *ConfigBuilder) Paths(paths ...string) *ConfigBuilder
- func (b *ConfigBuilder) Type(typeName string) *ConfigBuilder
- func (b *ConfigBuilder) Validator(v Validator) *ConfigBuilder
- type ConfigCenter
- type ConfigCenterConfig
- type ConfigData
- type ConfigModel
- type ConfigOption
- type ConfigWatcher
- type DefaultValidator
- func (v *DefaultValidator) AddCustomRule(field string, fn func(any) error)
- func (v *DefaultValidator) AddEnum(field string, values ...any)
- func (v *DefaultValidator) AddMax(field string, max int)
- func (v *DefaultValidator) AddMin(field string, min int)
- func (v *DefaultValidator) AddRegex(field, pattern string)
- func (v *DefaultValidator) AddRequired(fields ...string)
- func (v *DefaultValidator) Validate(data map[string]any) error
- type Loader
- type LoaderChain
- type LoaderModel
- type LoaderOption
- func WithEndpoints(endpoints []string) LoaderOption
- func WithFileName(name string) LoaderOption
- func WithLoaderEnv(env string) LoaderOption
- func WithLoaderFileType(fileType string) LoaderOption
- func WithLoaderKey(key string) LoaderOption
- func WithPaths(paths ...string) LoaderOption
- func WithPrefix(prefix string) LoaderOption
- func WithRemoteType(remoteType string) LoaderOption
- type PropertyBinder
- type TypeConverter
- type ValidationError
- type ValidationErrors
- type ValidationRule
- type ValidationRuleBuilder
- func (b *ValidationRuleBuilder) Build() Validator
- func (b *ValidationRuleBuilder) Custom(field string, fn func(any) error) *ValidationRuleBuilder
- func (b *ValidationRuleBuilder) Enum(field string, values ...any) *ValidationRuleBuilder
- func (b *ValidationRuleBuilder) Max(field string, max int) *ValidationRuleBuilder
- func (b *ValidationRuleBuilder) Min(field string, min int) *ValidationRuleBuilder
- func (b *ValidationRuleBuilder) Regex(field, pattern string) *ValidationRuleBuilder
- func (b *ValidationRuleBuilder) Required(fields ...string) *ValidationRuleBuilder
- type Validator
- type WatchCallback
- type WatchEvent
- type WatchManager
- func (m *WatchManager) AddSource(name string, ch chan WatchEvent)
- func (m *WatchManager) Close()
- func (m *WatchManager) GetSource(name string) (chan WatchEvent, bool)
- func (m *WatchManager) Notify(event WatchEvent)
- func (m *WatchManager) Register(key string, callback func(WatchEvent))
- func (m *WatchManager) Unregister(key string)
Constants ¶
const ( EventModify = "modify" // 配置修改 EventDelete = "delete" // 配置删除 EventCreate = "create" // 配置创建 )
热重载事件类型常量。
Variables ¶
This section is empty.
Functions ¶
func Bind ¶
Bind 将配置数据绑定到结构体
支持以下特性:
- env 标签:从扁平配置键映射到结构体字段
- 复杂类型自动转换:Duration、[]string、map[string]string 等
- 嵌套结构体:自动递归绑定嵌套字段
- validate 标签:集成验证规则(required、min、max 等)
参数:
- cfg: 配置数据源(Config 接口或 map[string]any)
- target: 目标结构体指针
返回:
- error: 绑定或验证错误
func BindProperties ¶
func BindProperties(target any, env *environment.Environment, opts ...BindOption) error
BindProperties 便捷函数:将配置绑定到目标结构体
func RegisterConverter ¶
func RegisterConverter(target any, fn TypeConverter)
RegisterConverter 注册自定义类型转换器
func Validate ¶
Validate 根据 validate 标签验证结构体字段
支持的验证规则:
- required: 字段不能为空
- min=N: 数值字段最小值,或字符串最小长度
- max=N: 数值字段最大值,或字符串最大长度
- enum=a,b,c: 枚举值限制
参数:
- target: 目标结构体指针
返回:
- error: 验证错误
func Watch ¶
func Watch(key string, callback WatchCallback) error
Watch 注册配置变更监听器。
当指定 key 的配置值发生变化时,触发回调函数。
示例:
config.Watch("database.url", func(event config.WatchEvent) {
log.Printf("配置变更: %s -> %v", event.Key, event.Value)
})
func WithDataID ¶
func WithDataID(dataID string) func(*ConfigCenterConfig)
WithDataID 设置配置中心的数据 ID(Nacos 使用)。
func WithFormat ¶
func WithFormat(format string) func(*ConfigCenterConfig)
WithFormat 设置配置中心的前缀(Etcd/Consul 使用)。
func WithGroup ¶
func WithGroup(group string) func(*ConfigCenterConfig)
WithGroup 设置配置中心的分组(Nacos 使用)。
func WithProfiles ¶
func WithProfiles(profiles []string) func(*ConfigCenterConfig)
WithProfiles 设置配置中心的命名空间(将 Profile 列表以逗号连接)。
Types ¶
type Config ¶
type Config interface {
// Get 获取指定键的原始值
Get(key string) any
// GetString 获取字符串值,类型不匹配时返回空字符串
GetString(key string) string
// GetInt 获取整数值,类型不匹配时返回 0
GetInt(key string) int
// GetBool 获取布尔值,类型不匹配时返回 false
GetBool(key string) bool
// GetAll 获取所有配置项的副本
GetAll() map[string]any
// Set 设置配置值
Set(key string, value any)
// Load 从 JSON 文件加载配置
Load(path string) error
// Save 保存配置到 JSON 文件
Save(path string) error
}
Config 配置接口。
提供统一的配置访问和管理功能。 支持多种数据类型(字符串、整数、布尔值等), 以及配置的加载和持久化。
使用示例 ¶
cfg := config.NewConfig()
cfg.Set("app.name", "my-app")
cfg.Set("server.port", 8080)
name := cfg.GetString("app.name")
port := cfg.GetInt("server.port")
type ConfigBuilder ¶
type ConfigBuilder struct {
// contains filtered or unexported fields
}
ConfigBuilder 配置构建器,支持链式配置和便捷加载
func (*ConfigBuilder) BuildAndLoad ¶
func (b *ConfigBuilder) BuildAndLoad() (*ConfigModel, error)
BuildAndLoad 构建并加载配置
func (*ConfigBuilder) EnvPrefix ¶
func (b *ConfigBuilder) EnvPrefix(prefix string) *ConfigBuilder
EnvPrefix 设置环境变量前缀
func (*ConfigBuilder) Environment ¶
func (b *ConfigBuilder) Environment(env string) *ConfigBuilder
Environment 设置环境
func (*ConfigBuilder) File ¶
func (b *ConfigBuilder) File(path string) *ConfigBuilder
File 设置配置文件完整路径
func (*ConfigBuilder) Loader ¶
func (b *ConfigBuilder) Loader(loader Loader, opts ...LoaderOption) *ConfigBuilder
Loader 设置加载器
func (*ConfigBuilder) Paths ¶
func (b *ConfigBuilder) Paths(paths ...string) *ConfigBuilder
Paths 设置配置搜索路径
func (*ConfigBuilder) Type ¶
func (b *ConfigBuilder) Type(typeName string) *ConfigBuilder
Type 设置配置类型
func (*ConfigBuilder) Validator ¶
func (b *ConfigBuilder) Validator(v Validator) *ConfigBuilder
Validator 设置验证器
type ConfigCenter ¶
type ConfigCenter interface {
Load() (ConfigData, error)
Watch(key string, callback func(ConfigData)) error
Close() error
}
ConfigCenter 配置中心接口。
定义远程配置的加载、监听和关闭行为。
type ConfigCenterConfig ¶
type ConfigCenterConfig struct {
Endpoints []string
Namespace string
Timeout time.Duration
DataID string
Group string
Prefix string
}
ConfigCenterConfig 配置中心连接配置。
func WithRemoteSource ¶
func WithRemoteSource(centerType string, endpoints []string, opts ...func(*ConfigCenterConfig)) *ConfigCenterConfig
WithRemoteSource 创建配置中心配置
便捷函数,用于创建 ConfigCenterConfig 实例。
参数:
- centerType: 配置中心类型 (nacos/etcd/consul)
- endpoints: 配置中心地址列表
- opts: 可选的配置中心选项
示例:
cfg := config.WithRemoteSource("nacos", []string{"127.0.0.1:8848"},
config.WithDataID("app-config"),
config.WithGroup("DEFAULT_GROUP"),
)
cfg := config.WithRemoteSource("etcd", []string{"127.0.0.1:2379"},
config.WithFormat("/config/myapp/"),
)
type ConfigModel ¶
type ConfigModel struct {
ConfigName string
ConfigFile string
ConfigPaths []string
ConfigType string
Env string
OptionName string
Config map[string]any
}
ConfigModel 配置模型。
存储配置构建的所有参数和最终配置数据。
func New ¶
func New(load func(*ConfigModel) error, opts ...ConfigOption) (*ConfigModel, error)
New 创建配置模型。
type ConfigWatcher ¶
type ConfigWatcher struct {
// contains filtered or unexported fields
}
ConfigWatcher 配置监听器,简化热重载使用
func (*ConfigWatcher) OnChange ¶
func (w *ConfigWatcher) OnChange(key string, callback func(event WatchEvent))
OnChange 注册配置变更回调
type DefaultValidator ¶
type DefaultValidator struct {
// contains filtered or unexported fields
}
DefaultValidator 默认验证器实现。
func (*DefaultValidator) AddCustomRule ¶
func (v *DefaultValidator) AddCustomRule(field string, fn func(any) error)
AddCustomRule 添加自定义验证规则
func (*DefaultValidator) AddEnum ¶
func (v *DefaultValidator) AddEnum(field string, values ...any)
AddEnum 添加枚举值验证
func (*DefaultValidator) AddMax ¶
func (v *DefaultValidator) AddMax(field string, max int)
AddMax 添加最大值验证
func (*DefaultValidator) AddMin ¶
func (v *DefaultValidator) AddMin(field string, min int)
AddMin 添加最小值验证
func (*DefaultValidator) AddRegex ¶
func (v *DefaultValidator) AddRegex(field, pattern string)
AddRegex 添加正则表达式验证
func (*DefaultValidator) AddRequired ¶
func (v *DefaultValidator) AddRequired(fields ...string)
AddRequired 添加必填字段验证
type Loader ¶
type Loader interface {
Load(opts ...LoaderOption) (Config, error)
Priority() int
Name() string
SupportsWatch() bool
}
Loader 配置加载器接口。
定义配置加载的统一方式,用于支持多种配置源。
type LoaderChain ¶
type LoaderChain struct {
// contains filtered or unexported fields
}
LoaderChain 配置加载器链.
用于管理多个加载器,并按优先级排序.
func (*LoaderChain) Len ¶
func (c *LoaderChain) Len() int
Len 返回加载器数量
实现 sort.Interface 接口,用于按优先级排序。
返回:
- int: 加载器数量
func (*LoaderChain) Less ¶
func (c *LoaderChain) Less(i, j int) bool
Less 比较两个加载器的优先级
实现 sort.Interface 接口,优先级数值越小的加载器排在越前面。
参数:
- i: 第一个加载器索引
- j: 第二个加载器索引
返回:
- bool: i 的优先级是否低于 j
func (*LoaderChain) Swap ¶
func (c *LoaderChain) Swap(i, j int)
Swap 交换两个加载器位置
实现 sort.Interface 接口。
参数:
- i: 第一个加载器索引
- j: 第二个加载器索引
type LoaderModel ¶
type LoaderModel struct {
Paths []string
FileName string
FileType string
Env string
Prefix string
RemoteType string
Endpoints []string
Key string
}
LoaderModel 配置加载器模型结构体。
type LoaderOption ¶
type LoaderOption func(*LoaderModel) error
LoaderOption 配置加载器选项函数类型。
func WithEndpoints ¶
func WithEndpoints(endpoints []string) LoaderOption
WithEndpoints 设置远程配置端点选项.
参数:
- endpoints: 端点地址列表
返回:
- LoaderOption: 加载器选项函数
func WithFileName ¶
func WithFileName(name string) LoaderOption
WithFileName 设置文件名选项.
参数:
- name: 文件名
返回:
- LoaderOption: 加载器选项函数
func WithLoaderEnv ¶
func WithLoaderEnv(env string) LoaderOption
WithLoaderEnv 设置环境选项.
参数:
- env: 环境名称
返回:
- LoaderOption: 加载器选项函数
func WithLoaderFileType ¶
func WithLoaderFileType(fileType string) LoaderOption
WithLoaderFileType 设置文件类型选项.
参数:
- fileType: 文件类型,如 json
返回:
- LoaderOption: 加载器选项函数
func WithLoaderKey ¶
func WithLoaderKey(key string) LoaderOption
WithLoaderKey 设置配置键选项.
参数:
- key: 配置键
返回:
- LoaderOption: 加载器选项函数
func WithPaths ¶
func WithPaths(paths ...string) LoaderOption
WithPaths 设置配置搜索路径选项.
参数:
- paths: 搜索路径列表
返回:
- LoaderOption: 加载器选项函数
func WithPrefix ¶
func WithPrefix(prefix string) LoaderOption
WithPrefix 设置环境变量前缀选项.
参数:
- prefix: 环境变量前缀
返回:
- LoaderOption: 加载器选项函数
func WithRemoteType ¶
func WithRemoteType(remoteType string) LoaderOption
WithRemoteType 设置远程配置类型选项.
参数:
- remoteType: 远程配置类型,如 etcd, consul, apollo
返回:
- LoaderOption: 加载器选项函数
type PropertyBinder ¶
type PropertyBinder struct {
// contains filtered or unexported fields
}
PropertyBinder 配置属性绑定器
将 Environment 中的配置值绑定到结构体字段。 支持嵌套结构体、切片、映射和自定义类型转换。
func NewPropertyBinder ¶
func NewPropertyBinder(env *environment.Environment) *PropertyBinder
NewPropertyBinder 创建配置属性绑定器
func (*PropertyBinder) Bind ¶
func (b *PropertyBinder) Bind(target any) error
Bind 将配置绑定到目标结构体
参数:
- target: 目标结构体指针
返回:
- error: 绑定错误
func (*PropertyBinder) WithPrefix ¶
func (b *PropertyBinder) WithPrefix(prefix string) *PropertyBinder
WithPrefix 设置配置前缀
func (*PropertyBinder) WithValidator ¶
func (b *PropertyBinder) WithValidator(v Validator) *PropertyBinder
WithValidator 设置验证器
type TypeConverter ¶
TypeConverter 类型转换函数类型
func GetConverter ¶
func GetConverter(target reflect.Type) (TypeConverter, bool)
GetConverter 获取指定类型的转换器
type ValidationError ¶
ValidationError 单个验证错误。
type ValidationRule ¶
ValidationRule 验证规则。
type ValidationRuleBuilder ¶
type ValidationRuleBuilder struct {
// contains filtered or unexported fields
}
ValidationRuleBuilder 验证规则构建器
func NewValidationRuleBuilder ¶
func NewValidationRuleBuilder() *ValidationRuleBuilder
NewValidationRuleBuilder 创建验证规则构建器
func (*ValidationRuleBuilder) Custom ¶
func (b *ValidationRuleBuilder) Custom(field string, fn func(any) error) *ValidationRuleBuilder
Custom 添加自定义规则
func (*ValidationRuleBuilder) Enum ¶
func (b *ValidationRuleBuilder) Enum(field string, values ...any) *ValidationRuleBuilder
Enum 添加枚举值
func (*ValidationRuleBuilder) Max ¶
func (b *ValidationRuleBuilder) Max(field string, max int) *ValidationRuleBuilder
Max 添加最大值限制
func (*ValidationRuleBuilder) Min ¶
func (b *ValidationRuleBuilder) Min(field string, min int) *ValidationRuleBuilder
Min 添加最小值限制
func (*ValidationRuleBuilder) Regex ¶
func (b *ValidationRuleBuilder) Regex(field, pattern string) *ValidationRuleBuilder
Regex 添加正则表达式
func (*ValidationRuleBuilder) Required ¶
func (b *ValidationRuleBuilder) Required(fields ...string) *ValidationRuleBuilder
Required 添加必填字段
type WatchEvent ¶
type WatchEvent struct {
Type string // modify, delete, create
Key string // 配置键
Value any // 配置值
Timestamp time.Time // 事件时间
Source string // 事件来源
}
WatchEvent 配置变更事件。
func NewWatchEvent ¶
func NewWatchEvent(eventType, key string, value any, source string) WatchEvent
NewWatchEvent 创建配置变更事件。
type WatchManager ¶
type WatchManager struct {
// contains filtered or unexported fields
}
WatchManager 配置热重载管理器。
管理配置变更的监听和通知。
func NewWatchManager ¶
func NewWatchManager() *WatchManager
NewWatchManager 创建热重载管理器实例。
返回:
- *WatchManager: 管理器实例
func (*WatchManager) AddSource ¶
func (m *WatchManager) AddSource(name string, ch chan WatchEvent)
AddSource 添加配置源.
参数:
- name: 配置源名称
- ch: 事件通道
func (*WatchManager) GetSource ¶
func (m *WatchManager) GetSource(name string) (chan WatchEvent, bool)
GetSource 获取配置源.
参数:
- name: 配置源名称
返回:
- chan WatchEvent: 事件通道
- bool: 是否存在
func (*WatchManager) Notify ¶
func (m *WatchManager) Notify(event WatchEvent)
Notify 通知所有监听器配置变更.
参数:
- event: 变更事件
func (*WatchManager) Register ¶
func (m *WatchManager) Register(key string, callback func(WatchEvent))
Register 注册配置变更监听器.
参数:
- key: 监听器标识
- callback: 回调函数
func (*WatchManager) Unregister ¶
func (m *WatchManager) Unregister(key string)
Unregister 取消配置变更监听.
参数:
- key: 监听器标识
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package environment 提供环境配置管理功能,用于 enhance 框架。
|
Package environment 提供环境配置管理功能,用于 enhance 框架。 |
|
Package refresh 提供配置刷新功能,用于 enhance 框架。
|
Package refresh 提供配置刷新功能,用于 enhance 框架。 |