Documentation
¶
Overview ¶
cyconf/cyconf.go
cyconf/default_tag.go
Index ¶
- Constants
- func ApplyDefaultTags(v interface{}) error
- func LoadConfig[T any](opts ...Option) (*T, error)
- type ConfigSource
- type EnvSource
- type FileGroup
- type FileSource
- type FlagSource
- type Option
- func WithDefaults(flagName, envVar, filePath string) Option
- func WithDotEnv(paths ...string) Option
- func WithEnv(envVar string) Option
- func WithFile(path string) Option
- func WithFileSearch(paths ...string) Option
- func WithFiles(paths ...string) Option
- func WithFlag(flagName, defaultPath string) Option
- func WithNoDotEnv() Option
- func WithNoExpandEnv() Option
- func WithTagName(name string) Option
Constants ¶
const (
// DefaultTagName tag 名称,用于指定默认值
DefaultTagName = "default"
)
Variables ¶
This section is empty.
Functions ¶
func ApplyDefaultTags ¶ added in v1.0.0
func ApplyDefaultTags(v interface{}) error
ApplyDefaultTags 递归遍历结构体,为没有从配置文件中获取到值的字段应用 tag 中的默认值 这个函数应该在 viper.Unmarshal 之后调用
func LoadConfig ¶
Types ¶
type ConfigSource ¶
type FileSource ¶
FileSource 指向一个配置文件(支持合并)
type FlagSource ¶
FlagSource 从命令行 flag 读取配置路径
type Option ¶
type Option func(*configLoader)
func WithDotEnv ¶ added in v1.0.0
WithDotEnv 设置自定义的 .env 文件搜索路径。 .env 加载默认启用,无需调用此选项即可自动加载 .env 文件。 已存在的环境变量不会被覆盖(与 12-Factor App 一致)。
默认搜索顺序(不调用 WithDotEnv 时): $CONFIG_DIR/.env → ${exe_dir}/.env → ./configs/.env → ./.env
用法:
// 使用默认路径(推荐)— 无需调用
cyconf.LoadConfig[config](
cyconf.WithFile("configs/config.yaml"),
)
// 指定自定义路径
cyconf.LoadConfig[config](
cyconf.WithDotEnv("/opt/app/.env", "/backup/.env"),
cyconf.WithFile("configs/config.yaml"),
)
func WithFileSearch ¶ added in v1.0.0
WithFileSearch 从多个候选路径中加载第一个存在的配置文件。 与 WithFile / WithFiles(全部加载/合并)不同,本选项是"搜索"语义,找到第一个即停止。 适用于配置文件位置不确定的场景(如开发 vs 部署环境路径不同)。
用法:
cyconf.LoadConfig[config](
cyconf.WithFileSearch(
"/etc/myapp/config.yaml",
"./configs/config.yaml",
"config.yaml",
),
)
func WithNoDotEnv ¶ added in v1.0.0
func WithNoDotEnv() Option
WithNoDotEnv 禁用 .env 文件的自动加载。
默认情况下,LoadConfig 会在加载配置前自动搜索并读取 .env 文件, 将其中的键值对注入系统环境变量。使用本选项可禁用此行为。
用法:
cyconf.LoadConfig[config](
cyconf.WithNoDotEnv(), // 不加载 .env
cyconf.WithFile("configs/config.yaml"),
)
func WithNoExpandEnv ¶ added in v1.0.0
func WithNoExpandEnv() Option
WithNoExpandEnv 禁用配置文件中的 ${VAR} 环境变量展开。
默认情况下,cyconf 会在读取配置文件内容后、反序列化之前, 对其中的 ${VAR} 引用执行 expandEnvWithDefault 展开,支持以下语法:
${VAR} → 替换为环境变量 VAR 的值,未设置则为空字符串
${VAR:-default} → 替换为环境变量 VAR 的值,未设置则使用 default
使用本 Option 可禁用此行为,此时 ${VAR} 在配置文件中将原样保留。
用法:
cyconf.LoadConfig[config](
cyconf.WithFile("configs/config.yaml"),
cyconf.WithNoExpandEnv(),
)
func WithTagName ¶ added in v1.0.0
WithTagName 自定义结构体字段映射使用的 tag 名称。
默认按配置文件类型自动推断("auto" 行为):
- .yaml/.yml → yaml
- .json → json
- .toml → toml
- 类型混合或不确定 → 回退到 mapstructure
如需显式使用 mapstructure tag,可设置 WithTagName("mapstructure")。
用法:
cyconf.LoadConfig[config](
cyconf.WithTagName("mapstructure"), // 显式使用 mapstructure tag
cyconf.WithFile("config.yaml"),
)