Use of YAML configuration files in the Go language

Source: Internet
Author: User

In this article, Yaml uses a third-party open source gopkg.in/yaml.v2 on GitHub.
How to use it specifically.
First step: Download

Go get gopkg.in/yaml.v2

Step two: Create a yaml file, such as Conf.yaml

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

It is important to note that there are spaces behind the colon in user:root, for example

Step three: Create a new go file, such as Main.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
}

Run Main.go, you can print out the user's value in the configuration file root

Reference article: http://blog.csdn.net/wangshubo1989/article/details/73784907

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.