使用viper解析ini配置文件

2年前 (2022) 程序员胖胖胖虎阿
127 0 0

在项目中,经常使用ini和yaml作为配置文件。

对于ini配置文件,一直使用https://github.com/go-ini/ini这个库来解析配置。主要是因为简单易用并且中文文档支持较好。

对于viper,之前是不支持ini配置的,关于viper为什么不支持ini,官方QA有一段解释

Q: Why not INI files?

A: Ini files are pretty awful. There’s no standard format, and they are hard to validate. Viper is designed to work with JSON, TOML or YAML files. If someone really wants to add this feature, I’d be happy to merge it. It’s easy to specify which formats your application will permit.

看来ini格式一直不受viper待见...

最近翻看viper文档的时候,发现在v1.6.0的版本中已经添加了对ini的支持,大概体验了下。

随便找了一个ini配置文件

# possible values : production, development
app_mode = development

[paths]
# Path to where grafana can store temp files, sessions, and the sqlite3 db (if that is used)
data = /home/git/grafana

[server]
# Protocol (http or https)
protocol = "http"

# The http port  to use
http_port = 9999

# Redirect to correct domain if host header does not match domain
# Prevents DNS rebinding attacks
enforce_domain = true
// 指定要解析的配置文件
viper.SetConfigFile("my.ini")
if err := viper.ReadInConfig(); err != nil {
    log.Fatal(err)
}
// 默认section为default
fmt.Printf("app_mode:%v\n", viper.GetString(`default.app_mode`))
fmt.Printf("server.protocol:%v\n", viper.GetString(`server.protocol`))

// 获取所有配置
all := viper.AllSettings()
fmt.Printf("%#v\n", all)

// 解析section到struct
server := struct {
  Protocol      string `mapstructure:"protocol"`
  HttpPort      int    `mapstructure:"http_port"`
  EnforceDomain bool   `mapstructure:"enforce_domain"`
}{}
if err := viper.UnmarshalKey("server", &server); err != nil {
    fmt.Println("ini解析到struct 异常: ", err)
} else {
    fmt.Println("struct: ", server)
}

输出

app_mode:development
server.protocol:http
map[string]interface {}{"default":map[string]interface {}{"app_mode":"development"}, "paths":map[string]interface {}{"data":"/home/git/grafana"}, "server":map[string]interface {}{"enforce_domain":"true", "http_port":"9999", "protocol":"http"}}
struct:  {http 9999 true}

可以看出,对于一些常用的功能使用起来也是比较简单方便的。

viper中提供如下方法来获取配置

  • Get(key string) : interface{}
  • GetBool(key string) : bool
  • GetFloat64(key string) : float64
  • GetInt(key string) : int
  • GetIntSlice(key string) : []int
  • GetString(key string) : string
  • GetStringMap(key string) : map[string]interface{}
  • GetStringMapString(key string) : map[string]string
  • GetStringSlice(key string) : []string
  • GetTime(key string) : time.Time
  • GetDuration(key string) : time.Duration
  • IsSet(key string) : bool
  • AllSettings() : map[string]interface{}

参考

https://github.com/spf13/viper

版权声明:程序员胖胖胖虎阿 发表于 2022年10月26日 上午10:56。
转载请注明:使用viper解析ini配置文件 | 胖虎的工具箱-编程导航

相关文章

暂无评论

暂无评论...