1. What is YAML?
Official website explanation
%YAML 1.2---YAML: YAML Ain't Markup LanguageWhat It Is: YAML is a human friendly data serialization standard for all programming languages.
2.yaml syntax
Yaml syntax, please refer to this man's, written in very detailed.
3. Golang parsing Yaml files
system Environment: MacOS, VIM 8.0, golang:go version go1.8 darwin/amd64
3.1 Creating a Yaml file
Vim First.yaml
The contents are as follows:
SiteName: seetaSiteAddr: BeiJingHttps: trueNginx: Port: 443 LogPath: "/var/log//nginx/nginx.log" Path: "/opt/nginx/"
3.2 Go parsing Yaml's package
3.2.1 Yaml.v2
This article uses: Gopkg.in/yaml.v2
import "Gopkg.in/yaml.v2"
3.2 Parsing yaml file code
package mainimport ( "fmt" "io/ioutil" "gopkg.in/yaml.v2")//Nginx nginx 配置type Nginx struct { Port int `yaml:"Port"` LogPath string `yaml:"LogPath"` Path string `yaml:"Path"`}//Config 系统配置配置type Config struct{ Name string `yaml:"SiteName"` Addr string `yaml:"SiteAddr"` HTTPS bool `yaml:"Https"` SiteNginx Nginx `yaml:"Nginx"`}func main() { var setting Config config, err := ioutil.ReadFile("./first.yaml") if err != nil { fmt.Print(err) } yaml.Unmarshal(config,&setting) fmt.Println(setting.Name) fmt.Println(setting.Addr) fmt.Println(setting.HTTPS) fmt.Println(setting.SiteNginx.Port) fmt.Println(setting.SiteNginx.LogPath) fmt.Println(setting.SiteNginx.Path)}
Introduction to Functions:
- Ioutil. ReadFile ("./first.yaml"): Read Yaml file information
- Yaml. Unmarshal ()
First input parameter: Gets ioutil. The value of ReadFile, for the []byte type
The second parameter outputs a parameter, which can be any type.
Reference:
The Yaml.v2 in Godoc
Yaml Source in GitHub