go yaml配置文件使用

下载

go get gopkg.in/yaml.v2

新建yaml文件

host: localhost:3306
user: root
pwd: 123456
dbname: test

这里需要注意,以user: root为例,冒号后面有空格

新建go文件

package main

import (
    "io/ioutil"
    "gopkg.in/yaml.v2"
    "fmt"
)

func main() {
   var c conf
   conf:=c.getConf()
   fmt.Println(conf.Host)
}

//profile variables
type conf struct {
    Host string `yaml:"host"`
    User string `yaml:"user"`
    Pwd string `yaml:"pwd"`
    Dbname string `yaml:"dbname"`
}
func (c *conf) getConf() *conf {
    yamlFile, err := ioutil.ReadFile("conf.yaml")
    if err != nil {
        fmt.Println(err.Error())
    }
    err = yaml.Unmarshal(yamlFile, c)
    if err != nil {
        fmt.Println(err.Error())
    }
    return c
}

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×