栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Go语言

go语言 解析yaml文件详解

Go语言 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

go语言 解析yaml文件详解

yaml格式文件作为配置文件、包管理文件,众多软件都在使用,go 语言通过 “gopkg.in/yaml.v2” 包,可以支持 yaml文件解析和处理。

文件conf.yaml 文件内容如下:
robot@ubuntu:~/gomod/src/yaml$ cat conf.yaml 
config:
  user:
    - Tom
    - Lily
    - Skay
 
  mqtt:
     host: localhost:1883
     username: test
     password: test
 
  http: {port: "8080", host: "127.0.0.1"}

如何使用 "gopkg.in/yaml.v2"包处理这个文件呢,实例代码如下:

实例代码
robot@ubuntu:~/gomod/src/yaml$ cat yaml.go 
package main

import (
	"os"
	"log"
	"fmt"
	"encoding/json"
	"gopkg.in/yaml.v2"
)

type HTTP struct {
	Port string `yaml:"port"`
	Host string `yaml:"host"`
}

type MQ struct {
	Host string `yaml:"host"`
	Username string `yaml:"username"`
	Password string `yaml:"password"`
}


type Debug struct {
	User []string `yaml:"user"`
	MQTT MQ `yaml:"mqtt"`
	Http HTTP `yaml:"http"`
}


type Config struct {
	Debug Debug `yaml:"config"`
}


func ReadYamlConfig(path string) (*Config,error){
	conf := &Config{}
	if f, err := os.Open(path); err != nil {
		return nil,err
	} else {
		yaml.NewDecoder(f).Decode(conf)
	}
	fmt.Println("conf: ", conf)
	return conf,nil
}

func main() {
	conf,err := ReadYamlConfig("conf.yaml")
	if err != nil {
		log.Fatal(err)
	}

	byts, err := json.Marshal(conf)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("string:",string(byts))
}

实例运行结果

如下:

robot@ubuntu:~/gomod/src/yaml$ ls
conf.yaml  go.mod  go.sum  yaml.go

robot@ubuntu:~/gomod/src/yaml$ go run yaml.go 
conf:  &{{[Tom Lily Skay] {localhost:1883 test test} {8080 127.0.0.1}}}
string: {"Debug":{"User":["Tom","Lily","Skay"],"MQTT":{"Host":"localhost:1883","Username":"test","Password":"test"},"Http":{"Port":"8080","Host":"127.0.0.1"}}}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/902630.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号