准备数据
app:
host: 127.0.0.1
port: 3306
username: root
password: root
path:
suffix: bucket
maxSize: 100
方式一、yaml.v2
package main
import (
"log"
"io/ioutil"
"gopkg.in/yaml.v2"
)
type App struct {
Host string `yaml:"host" json:"host"`
Port int `yaml:"port" json:"port"`
Username string `yaml:"username" json:"username"`
Password string `yaml:"password" json:"password"`
}
type Path struct {
Suffix string `yaml:"suffix" json:"suffix"`
MaxSize int `yaml:"maxSize" json:"maxsize"`
}
type Config struct {
App App `yaml:"app" json:"app"`
Path Path `yaml:"log" json:"log"`
}
func main() {
//通过ioutil导入配置文件
file, err := ioutil.ReadFile("./config.yml")
if err != nil {
log.Println(err.Error())
}
config := new(Config)
//将配置文件读取到结构体中
err = yaml.Unmarshal(file, &config)
if err != nil {
log.Println(err.Error())
}
username := config.App.Username
log.Println("username:" + username)
log.Println("MaxSize: ", config.Path.MaxSize)
}
方式二、Viper
1.viper支持的格式:JSON、TOML、YAML、HCL、Java properties、INI。
2.viper可以热加载配置文件。
3.使用
package main
import (
"log"
"github.com/spf13/viper"
)
type App struct {
Host string `yaml:"host" json:"host"`
Port int `yaml:"port" json:"port"`
Username string `yaml:"username" json:"username"`
Password string `yaml:"password" json:"password"`
}
type Path struct {
Suffix string `yaml:"suffix" json:"suffix"`
MaxSize int `yaml:"maxSize" json:"maxsize"`
}
type Config struct {
App App `yaml:"app" json:"app"`
Path Path `yaml:"log" json:"log"`
}
func main() {
//设置配置文件类型
viper.SetConfigType("yaml")
//导入配置文件
viper.SetConfigFile("./config.yml")
//读取配置文件
err := viper.ReadInConfig()
if err != nil {
log.Println(err.Error())
}
var config *Config
//将配置文件读到结构体中
err = viper.Unmarshal(&config)
if err != nil {
log.Println(err.Error())
}
username := config.App.Username
log.Println("username:" + username)
log.Println("MaxSize: ", config.Path.MaxSize)
}