yamlGolangyaml

导入依赖

go get gopkg.in/yaml.v3

config.yaml文件内容如下

database:
  mysql: 127.0.0.1
es:
  host: 127.0.0.1
  user: es
  pwd: 123

实例代码

// main.go
package main

import (
	"fmt"
	"io/ioutil"

	"gopkg.in/yaml.v2"
)

type Conf struct {
	Database Database `yaml:"database"`
	Es       Es       `yaml:"es"`
}
type Database struct {
	Mysql string `yaml:"mysql"`
}
type Es struct {
	Host string `yaml:"host"`
	User string `yaml:"user"`
	Pwd  string `yaml:"pwd"`
}
//读取yaml配置文件方法
func getConf() Conf {
	var conf Conf
	yamlFile, err := ioutil.ReadFile("./config.yaml")
	if err != nil {
		fmt.Println(err.Error())
	}
	err = yaml.Unmarshal(yamlFile, &conf)
	if err != nil {
		fmt.Println(err.Error())
	}
	return conf
}

func main() {
	fmt.Println(getConf().Database)
	fmt.Println(getConf().Database.Mysql)
}