Analysis of Golang Basic Learning-yaml file

Source: Internet
Author: User
Tags readfile

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:

    1. Ioutil. ReadFile ("./first.yaml"): Read Yaml file information
    2. 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

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.