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)
    }
    
  • 相关阅读:
    mysql int类型 int(11) 和int(2)区别
    mysql 用户 登陆 权限相关
    【转】ext4+delalloc造成单次写延迟增加的分析
    write 系统调用耗时长的原因
    【转】通过blktrace, debugfs分析磁盘IO
    win7 wifi热点
    【SystemTap】 Linux下安装使用SystemTap源码安装SystemTap
    pdflush进程介绍与优化【转】
    How to find per-process I/O statistics on Linux
    oom_killer
  • 原文地址:https://www.cnblogs.com/yuhaohao/p/15387265.html
Copyright © 2011-2022 走看看