go get github.com/spf13/viper
config.toml
title = "toml exaples"
redis = "127.0.0.1:3300"
[mysql]
host = "192.168.1.1"
ports = 3306
username = "root"
password = "root123456"
package main
import(
"fmt"
"github.com/spf13/viper"
)
// 读取配置文件config
type Config struct {
Redis string
MySQL MySQLConfig
}
type MySQLConfig struct {
Port int
Host string
Username string
Password string
}
func main() {
// 把配置文件读取到结构体上
var config Config
viper.SetConfigName("config")
viper.AddConfigPath(".")
err := viper.ReadInConfig()
if err != nil {
fmt.Println(err)
return
}
//将配置文件绑定到config上
viper.Unmarshal(&config)
fmt.Println("config: ", config, "redis: ", config.Redis)
}
config: {127.0.0.1:3300 {0 192.168.1.1 root root123456}} redis: 127.0.0.1:3300
读取多个配置,新增一个config1.json
{
"redis": "127.0.0.1:33000",
"mysql": {
"port": 3306,
"host": "127.0.0.1",
"username": "root",
"password": "123456"
}
}
package main
import (
"fmt"
"github.com/spf13/viper"
)
type Config struct {
Redis string
MySQL MySQLConfig
}
type MySQLConfig struct {
Port int
Host string
Username string
Password string
}
func main() {
// 读取 toml 配置文件
var config1 Config
vtoml := viper.New()
vtoml.SetConfigName("config")
vtoml.SetConfigType("toml")
vtoml.AddConfigPath(".")
if err := vtoml.ReadInConfig(); err != nil {
fmt.Println(err)
return
}
vtoml.Unmarshal(&config1)
fmt.Println("read config.toml")
fmt.Println("config: ", config1, "redis: ", config1.Redis)
// 读取 json 配置文件
var config2 Config
vjson := viper.New()
vjson.SetConfigName("config1")
vjson.SetConfigType("json")
vjson.AddConfigPath(".")
if err := vjson.ReadInConfig(); err != nil {
fmt.Println("bb",err)
return
}
vjson.Unmarshal(&config2)
fmt.Println("read config1.json")
fmt.Println("config: ", config2, "redis: ", config2.Redis)
}
# 输出
read config.toml
config: {127.0.0.1:3300 {0 192.168.1.1 root root123456}} redis: 127.0.0.1:3300
read config1.json
config: {127.0.0.1:33000 {3306 127.0.0.1 root 123456}} redis: 127.0.0.1:33000