config

package
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: Dec 24, 2025 License: Apache-2.0 Imports: 7 Imported by: 0

Documentation

Index

Constants

View Source
const (
	DefaultConfigFileName = "config.yml"
)

Variables

This section is empty.

Functions

func AllKeys

func AllKeys() ([]string, error)

AllKeys 获取所有配置键

使用场景:

  • ✅ 配置调试和诊断
  • ✅ 动态配置探索

示例:

keys, err := config.AllKeys()
if err != nil {
    log.Fatal(err)
}
fmt.Printf("当前配置项: %v\n", keys)

func Cleanup

func Cleanup()

Cleanup 清理全局配置状态,释放相关资源

使用场景:

  • ✅ 应用程序关闭时清理资源
  • ✅ 在需要重新初始化配置时使用
  • ✅ 微服务重启时的资源清理

示例:

defer config.Cleanup() // 应用退出时清理

// 重新初始化配置
config.Cleanup()
err := config.LoadConfig(&newCfg)

func GetBoolWithDefault

func GetBoolWithDefault(key string, defaultValue bool) (bool, error)

GetBoolWithDefault 获取布尔配置项,支持默认值

func GetClient

func GetClient(filePath ...string) (*viper.Viper, error)

GetClient 获取配置的viper客户端实例,提供完整的viper功能

返回已配置好的viper实例,支持:

  • 动态配置获取
  • 配置文件监听和热更新
  • 复杂的配置操作和验证
  • 所有viper原生功能

使用场景:

  • ✅ 需要动态配置访问的高级应用
  • ✅ 第三方库集成
  • ✅ 配置热更新和监听
  • ✅ 复杂的配置层级操作

返回:

  • *viper.Viper: 配置好的viper实例
  • error: 如果初始化过程中出现错误

注意: 如果之前没有调用过LoadConfig,会自动初始化配置

示例:

client, err := config.GetClient()
if err != nil {
    log.Fatal("获取配置客户端失败:", err)
}

// 动态获取配置
value := client.GetString("dynamic.feature.flag")

// 监听配置变化
client.OnConfigChange(func(e fsnotify.Event) {
    fmt.Println("配置文件发生变化:", e.Name)
})
client.WatchConfig()

// 设置配置项(测试环境)
client.Set("app.debug", true)

func GetDurationWithDefault

func GetDurationWithDefault(key string, defaultValue time.Duration) (time.Duration, error)

GetDurationWithDefault 获取时间间隔配置项,支持默认值

func GetDurationWithValidation

func GetDurationWithValidation(key string, defaultValue, min, max time.Duration) (time.Duration, bool, error)

GetDurationWithValidation 获取时间间隔配置项并进行范围验证

func GetFloat64WithDefault

func GetFloat64WithDefault(key string, defaultValue float64) (float64, error)

GetFloat64WithDefault 获取浮点数配置项,支持默认值

func GetFloat64WithValidation

func GetFloat64WithValidation(key string, defaultValue, min, max float64) (float64, bool, error)

GetFloat64WithValidation 获取浮点数配置项并进行范围验证

func GetInt64WithDefault

func GetInt64WithDefault(key string, defaultValue int64) (int64, error)

GetInt64WithDefault 获取64位整数配置项,支持默认值

func GetIntWithDefault

func GetIntWithDefault(key string, defaultValue int) (int, error)

GetIntWithDefault 获取整数配置项,支持默认值

func GetIntWithValidation

func GetIntWithValidation(key string, defaultValue, min, max int) (int, bool, error)

GetIntWithValidation 获取整数配置项并进行范围验证

参数:

  • key: 配置键
  • defaultValue: 默认值
  • min, max: 有效范围(包含边界)

返回:

  • value: 配置值(如果超出范围则返回默认值)
  • isValid: 是否在有效范围内
  • error: 如果获取配置客户端失败

使用场景:

  • ✅ 需要范围验证的数值配置
  • ✅ 端口号、连接数等有限制的配置

示例:

port, valid, err := config.GetIntWithValidation("app.port", 8080, 1, 65535)
if err != nil {
    log.Fatal(err)
}
if !valid {
    log.Warn("端口配置超出有效范围,使用默认值")
}

func GetSizeInBytesWithDefault

func GetSizeInBytesWithDefault(key string, defaultValue int) (uint, error)

GetSizeInBytesWithDefault 获取字节大小配置项,支持默认值

func GetStringMapStringSliceWithDefault

func GetStringMapStringSliceWithDefault(key string, defaultValue map[string][]string) (map[string][]string, error)

GetStringMapStringSliceWithDefault 获取字符串到字符串切片的映射配置项,支持默认值

func GetStringMapStringWithDefault

func GetStringMapStringWithDefault(key string, defaultValue map[string]string) (map[string]string, error)

GetStringMapStringWithDefault 获取字符串到字符串的映射配置项,支持默认值

func GetStringMapWithDefault

func GetStringMapWithDefault(key string, defaultValue map[string]interface{}) (map[string]interface{}, error)

GetStringMapWithDefault 获取字符串映射配置项,支持默认值

func GetStringSliceWithDefault

func GetStringSliceWithDefault(key string, defaultValue []string) ([]string, error)

GetStringSliceWithDefault 获取字符串切片配置项,支持默认值

func GetStringWithDefault

func GetStringWithDefault(key, defaultValue string) (string, error)

GetStringWithDefault 获取字符串配置项,支持默认值

参数:

  • key: 配置键(支持嵌套,如 "app.name")
  • defaultValue: 默认值

使用场景:

  • ✅ 简单的动态配置获取
  • ✅ 需要默认值的配置项

返回:

  • string: 配置值或默认值
  • error: 如果获取配置客户端失败

示例:

appName, err := config.GetStringWithDefault("app.name", "默认应用名")
if err != nil {
    log.Fatal(err)
}

func GetTimeWithDefault

func GetTimeWithDefault(key string, defaultValue time.Time) (time.Time, error)

GetTimeWithDefault 获取时间配置项,支持默认值

func GetUint64WithDefault

func GetUint64WithDefault(key string, defaultValue uint64) (uint64, error)

GetUint64WithDefault 获取64位无符号整数配置项,支持默认值

func GetUintWithDefault

func GetUintWithDefault(key string, defaultValue uint) (uint, error)

GetUintWithDefault 获取无符号整数配置项,支持默认值

func IsSet

func IsSet(key string) (bool, error)

IsSet 检查配置项是否已设置

使用场景:

  • ✅ 条件配置加载
  • ✅ 可选功能的开关检查

示例:

if exists, err := config.IsSet("features.advanced_mode"); err == nil && exists {
    // 启用高级功能
}

func LoadConfig

func LoadConfig(config interface{}, filePath ...string) error

LoadConfig 加载配置文件并将其解析到提供的结构体中

参数:

  • config: 指向要填充的配置结构体的指针
  • filePath: 可选的自定义配置文件路径(如果为空,则使用默认路径 config.yml)

功能特性:

  • 默认在项目根目录查找 config.yml 文件
  • 支持自定义配置文件路径
  • 环境变量优先于配置文件中的值
  • 自动支持 YAML, JSON, TOML 等格式
  • 环境变量名自动转换(如 app.name -> APP_NAME)
  • 自动从 APP_NAME 环境变量获取前缀(如果设置了 APP_NAME=myapp,则环境变量为 MYAPP_*)

环境变量前缀规则:

  • 如果设置了 APP_NAME 环境变量,则使用其值作为前缀
  • 例如:APP_NAME=myapp 时,配置键 app.port 对应环境变量 MYAPP_APP_PORT
  • 如果未设置 APP_NAME,则直接使用无前缀的环境变量(如 APP_PORT)
  • 当配置文件和环境变量都有 app_name 时,环境变量优先级最高

返回:

  • error: 如果加载或解析过程中出现错误

使用场景:

  • ✅ 推荐用于大多数应用(约80%的使用场景)
  • ✅ 适合配置结构相对固定的应用
  • ✅ 提供类型安全和编译时检查

示例:

type AppConfig struct {
    App struct {
        Name string `mapstructure:"name"`
        Port int    `mapstructure:"port"`
    } `mapstructure:"app"`
}

// 基础用法
var config AppConfig
err := LoadConfig(&config) // 使用默认路径和自动前缀检测

// 自定义配置文件路径
err := LoadConfig(&config, "custom/config.yml")

// 环境变量示例:
// 不使用前缀: APP_NAME未设置时
//   export APP_PORT=8080
// 使用前缀: export APP_NAME=myapp 时
//   export MYAPP_APP_PORT=8080

func MustGetBoolWithDefault

func MustGetBoolWithDefault(key string, defaultValue bool) bool

MustGetBoolWithDefault 获取布尔配置项,如果失败则panic

func MustGetClient

func MustGetClient(filePath ...string) *viper.Viper

MustGetClient 获取配置客户端,如果失败则panic

这是GetClient的panic版本,适用于配置初始化失败应该终止程序的场景

使用场景:

  • ✅ 应用启动阶段,配置加载失败应该终止程序
  • ✅ 简化错误处理的场景

示例:

client := config.MustGetClient()
value := client.GetString("app.name")

func MustGetDurationWithDefault

func MustGetDurationWithDefault(key string, defaultValue time.Duration) time.Duration

MustGetDurationWithDefault 获取时间间隔配置项,如果失败则panic

func MustGetFloat64WithDefault

func MustGetFloat64WithDefault(key string, defaultValue float64) float64

MustGetFloat64WithDefault 获取浮点数配置项,如果失败则panic

func MustGetInt64WithDefault

func MustGetInt64WithDefault(key string, defaultValue int64) int64

MustGetInt64WithDefault 获取64位整数配置项,如果失败则panic

func MustGetIntWithDefault

func MustGetIntWithDefault(key string, defaultValue int) int

MustGetIntWithDefault 获取整数配置项,如果失败则panic

func MustGetSizeInBytesWithDefault

func MustGetSizeInBytesWithDefault(key string, defaultValue int) uint

MustGetSizeInBytesWithDefault 获取字节大小配置项,如果失败则panic

func MustGetStringMapStringSliceWithDefault

func MustGetStringMapStringSliceWithDefault(key string, defaultValue map[string][]string) map[string][]string

MustGetStringMapStringSliceWithDefault 获取字符串到字符串切片的映射配置项,如果失败则panic

func MustGetStringMapStringWithDefault

func MustGetStringMapStringWithDefault(key string, defaultValue map[string]string) map[string]string

MustGetStringMapStringWithDefault 获取字符串到字符串的映射配置项,如果失败则panic

func MustGetStringMapWithDefault

func MustGetStringMapWithDefault(key string, defaultValue map[string]interface{}) map[string]interface{}

MustGetStringMapWithDefault 获取字符串映射配置项,如果失败则panic

func MustGetStringSliceWithDefault

func MustGetStringSliceWithDefault(key string, defaultValue []string) []string

MustGetStringSliceWithDefault 获取字符串切片配置项,如果失败则panic

func MustGetStringWithDefault

func MustGetStringWithDefault(key, defaultValue string) string

MustGetStringWithDefault 获取字符串配置项,如果失败则panic

func MustGetTimeWithDefault

func MustGetTimeWithDefault(key string, defaultValue time.Time) time.Time

MustGetTimeWithDefault 获取时间配置项,如果失败则panic

func MustGetUint64WithDefault

func MustGetUint64WithDefault(key string, defaultValue uint64) uint64

MustGetUint64WithDefault 获取64位无符号整数配置项,如果失败则panic

func MustGetUintWithDefault

func MustGetUintWithDefault(key string, defaultValue uint) uint

MustGetUintWithDefault 获取无符号整数配置项,如果失败则panic

func ResetGlobalState

func ResetGlobalState()

ResetGlobalState 重置全局配置状态(主要用于测试)

注意: 这是一个内部函数,生产代码请使用 Cleanup()

Types

This section is empty.

Jump to

Keyboard shortcuts

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