golang读取各种配置文件(ini、json、yaml)
作者:FootMark.run
日常项目中,读取各种配置文件是避免不了的,本文主要介绍了golang读取各种配置文件(ini、json、yaml),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
日常项目中,读取各种配置文件是避免不了的,这里介绍一个能读取多种配置文件的库,viper
viper读取ini文件
config := viper.New()
config.AddConfigPath("./conf/") // 文件所在目录
config.SetConfigName("b") // 文件名
config.SetConfigType("ini") // 文件类型
if err := config.ReadInConfig(); err != nil {
if _, ok := err.(viper.ConfigFileNotFoundError); ok {
fmt.Println("找不到配置文件..")
} else {
fmt.Println("配置文件出错..")
}
}
host := config.GetString("redis.host") // 读取配置
fmt.Println("viper load ini: ", host)
b.ini文件如下
[mysql] username='root' password='123456' [redis] host='127.0.0.1' poet=3306 [mongodb] user='admin' password='admin'
viper读取json文件
config := viper.New()
config.AddConfigPath("./conf/")
config.SetConfigName("c")
config.SetConfigType("json")
if err := config.ReadInConfig(); err != nil {
if _, ok := err.(viper.ConfigFileNotFoundError); ok {
fmt.Println("找不到配置文件..")
} else {
fmt.Println("配置文件出错..")
}
}
version := config.GetString("version")
origin := config.GetString("host.origin")
fmt.Println(version)
fmt.Println(origin)
// 读取到map中
host := config.GetStringMapString("host")
fmt.Println(host)
fmt.Println(host["origin"])
fmt.Println(host["port"])
allSettings := config.AllSettings()
fmt.Println(allSettings)
c.json文件如下
{
"version": "2.0",
"secret": "footmark",
"host": {
"origin": "http://www.baidu.com",
"port": 8080
}
}
viper读取yaml文件
config := viper.New()
config.AddConfigPath("./conf/")
config.SetConfigName("a")
config.SetConfigType("yaml")
if err := config.ReadInConfig(); err != nil {
if _, ok := err.(viper.ConfigFileNotFoundError); ok {
fmt.Println("找不到配置文件..")
} else {
fmt.Println("配置文件出错..")
}
}
host := config.GetString("database.host")
fmt.Println("viper load yml: ", host)
allSettings := config.AllSettings()
fmt.Println(allSettings)
a.yaml文件如下
database: host: 127.0.0.1 user: root dbname: test pwd: 123456
viper常用方法
// 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{}
到此这篇关于golang读取各种配置文件(ini、json、yaml)的文章就介绍到这了,更多相关golang读取配置文件 内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
