-
yaml配置文件
host:
localhost:3306
user:
root
pwd:
112233
dbname:
1 -
安装yaml读取工具
go get gopkg.in/yaml.v2
-
从yaml文件读取配置
package main
import (
"fmt"
"gopkg.in/yaml.v2"
"os"
)
type Conf struct {
Host string `yaml:"host"`
User string `yaml:"user"`
Pwd string `yaml:"pwd"`
Dbname string `yaml:"dbname"`
}
func (c *Conf) getConf() (*Conf, error) {
yamlFile, err := os.ReadFile("yaml配置文件路径")
if err != nil {
return nil, err
}
err = yaml.Unmarshal(yamlFile, c)
if err != nil {
return nil, err
}
return c, nil
}
func main() {
var c Conf
cfg, err := c.getConf()
if err != nil {
fmt.Println("配置读取失败,err:", err.Error())
return
}
fmt.Println(cfg.Pwd)
}