首页 > 其他 > 详细

Go解析Yaml文件

时间:2021-06-25 17:11:56      阅读:13      评论:0      收藏:0      [点我收藏+]

Yaml 文件内容(test.yaml)

cache:
  enable : false
  list : [redis,mongoDB]
mysql:
  user : root
  password : wangJiLe
  host : 11.22.33.44
  port : 3306
  name : world

Go解析test.yaml文件(gopkg.in/yaml.v2包)

  • Goalng版本1.16.5
go mod init demo
go get gopkg.in/yaml.v2

解析代码如下

package main

import (
	"fmt"
	"io/ioutil"

	yaml "gopkg.in/yaml.v2"
)

type Yaml struct {
	Cache struct {
		Enable bool     `yaml:"enable"`
		List   []string `yaml:"list"`
	}
	MySQL struct {
		User     string `yaml:"user"`
		Password string `yaml:"password"`
		Host     string `yaml:"host"`
		Port     string `yaml:"port"`
		Name     string `yaml:"name"`
	}
}

func main() {
	var conf Yaml
	yamlFile, err := ioutil.ReadFile("test.yaml")
	if err != nil {
		fmt.Println(err)
		return
	}
	if err = yaml.Unmarshal(yamlFile, &conf); err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(conf.MySQL.Host)
	fmt.Println(conf.MySQL.Name)
	fmt.Println(conf.MySQL.Password)
	fmt.Println(conf.MySQL.Port)
	fmt.Println(conf.MySQL.User)
	fmt.Println(conf.Cache.Enable)

	for _, v := range conf.Cache.List {
		fmt.Println("Cache:", v)
	}
}

编译,运行

go build 

./demo
11.22.33.44
world
wangJiLe
3306
root
false
Cache: redis
Cache: mongoDB

Go解析Yaml文件

原文:https://www.cnblogs.com/liy36/p/14931256.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!