zoukankan      html  css  js  c++  java
  • Golang解析yaml文件

    一.具体思路

    将配置yaml文件内容解析为我们定义好的struct,这种比较简单,如果想获取对应的值,直接获取即可。

    二.实现步骤

    • 首先根据配置文件的内容定义一个结构体Config,结构体类型和yaml中的属性配置了映射,这样后面解析的时候可以将值设置到对应的属性上
    • 通过ioutil的ReadFile方法读取配置文件的内容
    • 定义一个结构体变量
    • 调用yaml的Unmarshal方法来解析文件的数据到结构体对象config中,注意这里必须传递结构体对下的地址&config。

    三.举例说明

    这里,我们定义一个yaml配置文件:

    cat config.yaml
    app:
      name: demoApp  
    memcache:
      enable : false
      list : [redis, rabbitmq]
    mysql:
      user : root
      password : mypassword
      host : 192.168.1.1
      port : 3306
      dbname : mydb1
    
    package main 
    
    import (
    	"fmt"
    	"io/ioutil"
    	"log"
    	yaml "gopkg.in/yaml.v2"
    )
    
    type Config struct {
    	App struct {
    		Name string `yaml:"name"`
    	}
    	MemCache struct {
    		Enable bool `yaml:"enable"`
    		List []string `yaml:"list"`
    	}
    	Mysql struct {
    		User string `yaml:"user"`
    		PassWord string `yaml:"password"`
    		Host string `yaml:"host"`
    		Port int32 `yaml:"port"`
    		DbName string `yaml:"dbname"`
    	}
    }
    
    func main() {
    	var config Config
    	File, err := ioutil.ReadFile("config.yml")
    	if err != nil {
    		log.Printf("读取配置文件失败 #%v", err)
    	}
    	err = yaml.Unmarshal(File, &config)
    	if err != nil {
    		log.Fatalf("解析失败: %v", err)
    	}
    	fmt.Printf("App name is: %v
    ", config.App.Name)
    	fmt.Printf("Mysql port is: %d
    ", config.Mysql.Port)
    }
    
  • 相关阅读:
    LeetCode90.子集 ||
    Ubuntu下的Matlab安装
    FAQ
    青石板
    交叉熵损失函数
    tf常用函数
    激活函数
    SGD和GD的区别
    卷积神经网络
    Ubuntu安装Matlab2016b
  • 原文地址:https://www.cnblogs.com/yuhaohao/p/15387265.html
Copyright © 2011-2022 走看看