configs

package
v0.2.0-alpha.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 4, 2026 License: Apache-2.0 Imports: 7 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Manager

type Manager[T any] struct {
	// contains filtered or unexported fields
}

Manager 是一个泛型配置管理器,支持从环境变量、命令行参数和动态映射中加载配置 配置加载的优先级顺序为:默认值 < 环境变量 < 命令行参数 < 动态映射(ParseMap) 该管理器是线程安全的,可以在并发环境中安全使用

func NewManager

func NewManager[T any](def *T) *Manager[T]

NewManager 创建一个新的配置管理器实例 参数说明:

  • def: 默认配置结构体指针,如果为 nil 则使用类型 T 的零值作为默认配置

创建管理器时会自动执行以下操作:

  1. 使用默认配置初始化配置对象
  2. 解析环境变量并更新配置(通过字段的 "env" 标签)
  3. 解析命令行参数并更新配置(通过字段的 "flag" 标签)

使用示例:

type Config struct {
    Port    int    `env:"PORT" flag:"port" desc:"服务端口"`
    Debug   bool   `env:"DEBUG" flag:"debug" desc:"调试模式"`
    LogFile string `env:"LOG_FILE" flag:"log-file" desc:"日志文件路径"`
}
mgr := NewManager(&Config{Port: 8080, Debug: false})

func (*Manager[T]) ParseMap

func (m *Manager[T]) ParseMap(data map[string]string)

ParseMap 从 map 中解析配置值并更新配置(线程安全) 参数说明:

  • data: 键值对映射,键为配置结构体的字段名(区分大小写),值为字符串格式的配置值

该函数会遍历 map 中的每个键值对,尝试将值解析并设置到对应的配置字段中。 map 的键必须与配置结构体的字段名完全匹配(区分大小写)。 支持的字段类型包括:string、bool、int、int32、int64、float32、float64

行为说明:

  • 如果 map 为 nil,函数直接返回,不进行任何操作
  • 如果 map 中的键在配置结构体中不存在,会记录警告日志并跳过该键
  • 如果字段不可设置(如未导出的字段),会记录警告日志并跳过
  • 对于数值类型,会进行字符串到数值的转换,转换失败时会记录警告日志但不中断执行

使用示例:

mgr.ParseMap(map[string]string{
    "Port":    "9090",
    "Debug":   "true",
    "LogFile": "/var/log/app.log",
})

func (*Manager[T]) Vars

func (m *Manager[T]) Vars() *T

Vars 返回当前配置的只读副本(线程安全) 返回值是指向配置结构体的指针,调用者不应修改返回的配置对象 如果需要更新配置,请使用 ParseMap 方法

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL