golang 读取YAML配置文件

YAML配置

参考配置文件config.yaml

1
2
3
4
5
6
7
8
languages:
- Ruby
- Perl
- Python
Nginx:
Port: 443
LogPath: "/var/log//nginx/nginx.log"
Path: "/opt/nginx/"

安装yaml包

1
go get gopkg.in/yaml.v2

结构体解析

1
2
3
4
5
6
7
8
9
10
type Nginx struct {
Port int `yaml:"Port"`
LogPath string `yaml:"LogPath"`
Path string `yaml:"Path"`
}

type language struct {
Languages []string
SiteNginx Nginx `yaml:"Nginx"`
}

解析YAML

1
2
3
4
5
6
7
8
9
10
11
var language language

file, err := ioutil.ReadFile("config.yaml")
if err != nil {
log.Printf("yamlFile.Get err #%v ", err)
}

err = yaml.Unmarshal(file, &language)
if err != nil {
log.Fatalf("Unmarshal: %v", err)
}

实例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39

package main

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

type Nginx struct {
Port int `yaml:"Port"`
LogPath string `yaml:"LogPath"`
Path string `yaml:"Path"`
}

type language struct {
Languages []string
SiteNginx Nginx `yaml:"Nginx"`
}

func main(){
var language language

file, err := ioutil.ReadFile("config.yaml")
if err != nil {
log.Printf("读取配置文件失败 #%v ", err)
}

err = yaml.Unmarshal(file, &language)
if err != nil {
log.Fatalf("解析失败: %v", err)
}

fmt.Println(language.Languages)
fmt.Println(language.SiteNginx.Port)
fmt.Println(language.SiteNginx.LogPath)
fmt.Println(language.SiteNginx.Path)
}