• Golang 多种配置文件解析


    Golang 配置文件相关操作

    本文以读取数据库配置文件为例

    1、JSON 文件

    package main
    
    /*
     解析 json 格式的配置文件
    文件内容如下:
    {
      "type": "json",
      "postgres": {
        "host": "localhost",
        "port": 5432,
        "username": "postgres",
        "password": "postgres",
        "dbname": "bubble"
      }
    }
    */
    import (
    	"encoding/json"
    	"fmt"
    	"io/ioutil"
    	"os"
    )
    
    // 定义第一级配置文件的结构体
    type Config struct {
    	Type     string
    	Postgres DbConf // 数据类型为第二级配置文件的结构体名称
    }
    
    // 定义第二级配置文件的结构体   注意数据类型
    type DbConf struct {
    	Host     string `json:"host"`
    	Port     uint   `json:"port"`
    	Username string `json:"username"`
    	Password string `json:"password"`
    	DbName   string `json:"dbname"`
    }
    
    // 定义配置文件结构体
    type JsonStruct struct {
    }
    
    // 创建配置文件的构造函数
    func NewJsonStruct() *JsonStruct {
    	return &JsonStruct{}
    }
    
    // 加载配置文件
    func (jt *JsonStruct) Load(filename string, v interface{}) {
    	// 读取配置文件
    	data, err := ioutil.ReadFile(filename)
    	if err != nil {
    		return
    	}
    	// 解析配置文件
    	err = json.Unmarshal(data, v)
    	if err != nil {
    		return
    	}
    
    }
    
    func main() {
    	JsonParse := NewJsonStruct()
    	v := Config{}
    	// 获取配置文件路径
    	osGwd, _ := os.Getwd()
    	confPath := osGwd + "/conf_json.json"
    	// 加载配置文件
    	JsonParse.Load(confPath, &v)
    	fmt.Printf("配置文件的类型为 %s \n", v.Type)
    	fmt.Printf("PG 数据库的配置为 %s \n", v.Postgres)
    }
    
    

    2、YAML 文件(推荐)

    package main
    /*
    解析 yaml 格式的配置文件
    文件内容如下:
    database:
      postgres:
        host: localhost
        port: 5432
        username: postgres
        password: postgres
        dbname: bubble
    } */
    
    import (
    	"fmt"
    	"gopkg.in/yaml.v2"
    	"io/ioutil"
    	"os"
    )
    
    type YamlStruct struct {
    }
    
    func NewYamlStruct() *YamlStruct {
    	return &YamlStruct{}
    }
    
    type YamlConfig struct {
    	DataBase DataBase `yaml:"database"`
    }
    
    type DataBase struct {
    	PgConf PgConf `yaml:"postgres"`
    }
    
    type PgConf struct {
    	Host     string `yaml:"host"`
    	Port     string `yaml:"port"`
    	Username string `yaml:"username"`
    	Password string `yaml:"password"`
    	DbName   string `yaml:"dbname"`
    }
    
    func (yam *YamlStruct) Load(filename string, v interface{}) {
    	data, err := ioutil.ReadFile(filename)
    	if err != nil {
    		panic(err.Error())
    	}
    	err = yaml.Unmarshal(data, v)
    	if err != nil {
    		panic(err.Error())
    	}
    }
    
    func main() {
    	YamlStruct := NewYamlStruct()
    	v := YamlConfig{}
    	osGwd, _ := os.Getwd()
    	confPath := osGwd + "/conf_yaml.yaml"
    	YamlStruct.Load(confPath, &v)
    	fmt.Printf("配置文件的数据为 %s \n", v.DataBase)
    }
    
    

    3、INI 文件

    package main
    
    /*
     解析 ini 格式的配置文件
    文件内容如下:
    mode=debug
    
    [postgres]
    host=localhost
    port=5432
    username=postgres
    password=postgres
    dbname=bubble
     */
    
    import (
    	"fmt"
    	"github.com/go-ini/ini"
    	"os"
    )
    
    //type Postgres struct {
    //	Host     string
    //	Port     uint
    //	Username string
    //	Password string
    //	DbName   string
    //}
    
    func main() {
    	osGwd, _ := os.Getwd()
    	confPath := osGwd + "/conf_ini.ini"
    	config, err := ini.Load(confPath)
    	if err != nil {
    		panic(err.Error())
    	}
    	// 可以直接读取配置,并设置默认值
    	mode := config.Section("").Key("mode").MustString("debug")
    	fmt.Println(mode)
    	postgres, err := config.GetSection("postgres")
    	if err != nil {
    		panic(err.Error())
    	}
    	// 可通过 Key 去取值
    	fmt.Println(postgres.Key("host"))  // localhost
    	fmt.Println(postgres.Keys())       //  [localhost 5432 postgres postgres bubble]
    	fmt.Println(postgres.KeyStrings()) // [host port username password dbname]
    }
    
    
  • 相关阅读:
    NoSQL数据库 Couchbase Server
    百度推广账户搭建思路
    禅道发邮件配置
    ASP 500错误解决方法
    MYSQL无法连接,提示10055错误尝试解决
    制作不随浏览器滚动的DIV-带关闭按钮
    [CSS3] :nth-child的用法
    [JS] 四角度旋转特效
    [JS] 瀑布流加载
    [CSS3] 二级下拉导航
  • 原文地址:https://www.cnblogs.com/zhangweijie01/p/15829800.html
Copyright © 2020-2023  润新知