Go語言解析YAML配置文件案例


          Go語言解析YAML配置文件案例

                                 作者:尹正傑

版權聲明:原創作品,謝絕轉載!否則將追究法律責任。

 

 

 

一.yaml配置文件

################### Springboard machine Configuration Example #########################

#================================ General ======================================
general:
  # 使用的 cpu 核數,默認使用操作系統的所有 cpu
  max_procs_enable: true
  # log 文件路徑
  log_path: /etc/springboardMchine/seelog.xml
  # debug 模式
  debug: true
#================================ HTTP API ======================================
# 用來以 http server 的形式提供對外的api
api:
  host: 0.0.0.0
  port: 8080
#================================ mysql ======================================
#  mysql配置
mysql:
  host: 172.200.1.254
  port: 3306
  name: jumpserver
  user: jason
  password: yinzhengjie

# cache 配置
cache:
  host: 172.200.1.254
  port: 6379
  password: yinzhengjie
  db: 0
#========== rpc ===========
#rpc 配置
rpc:
  host: 0.0.0.0
  port: 8888

 

二.自定義解析包

package config

import (
    "errors"
    "fmt"
    "github.com/toolkits/file"
    "gopkg.in/yaml.v1"
)

//根據配置文件定義與之對應的結構體字段
type GeneralConfig struct {
    LogPath        string `yaml:"log_path"`
    Debug          bool   `yaml:"debug"`
    MaxProcsEnable bool   `yaml:max_procs_enable`
}

//根據定義的結構體,將配置文件的數據手動生成一個結構體對象
func newGeneralConfig() *GeneralConfig {
    return &GeneralConfig{
        LogPath:        "/etc/springboardMchine/seelog.xml",
        Debug:          true,
        MaxProcsEnable: true,
    }
}

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

func newAPIConfig() *APIConfig {
    return &APIConfig{
        Host: "0.0.0.0",
        Port: 8080,
    }
}

type MysqlConfig struct {
    Host     string `yaml:"host"`
    Name     string `yaml:"name"`
    Port     int    `yaml:"port"`
    Password string `yaml:"password"`
    User     string `yaml:"user"`
}

func newMysqlConfig() *MysqlConfig {
    return &MysqlConfig{
        Host:     "172.200.1.254",
        Name:     "jumpserver",
        Port:     3306,
        User:     "jason",
        Password: "yinzhengjie",
    }
}

type CacheConfig struct {
    Host     string `yaml:""host`
    Port     int    `yaml:"port"`
    Password string `yaml:"password"`
    Db       int    `yaml:"db"`
}

func newCacheConfig() *CacheConfig {
    return &CacheConfig{
        Host:     "172.200.1.254",
        Port:     6379,
        Db:       0,
        Password: "yinzhengjie",
    }
}

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

func newRpcConfig() *RpcConfig {
    return &RpcConfig{
        Host: "0.0.0.0",
        Port: 8888,
    }
}

//定義一個結構體,將上述定義的結構體進行封裝
type ConfigYaml struct {
    Mysql     *MysqlConfig   `yaml:"mysql"`
    API       *APIConfig     `yaml:"api"`
    RpcClient *RpcConfig     `yaml:"rpc"`
    Cache     *CacheConfig   `yaml:"cache"`
    General   *GeneralConfig `yaml:"general"`
}

//使用封裝后的結構體進行實例化
var (
    Config *ConfigYaml = &ConfigYaml{
        Mysql:     newMysqlConfig(),
        API:       newAPIConfig(),
        RpcClient: newRpcConfig(),
        Cache:     newCacheConfig(),
        General:   newGeneralConfig(),
    }
)

//定義連接數據庫的函數
func DatabaseDialString() string {
    return fmt.Sprintf("%s:%s@%s(%s:%d)/%s?charset=%s",
        Config.Mysql.User,
        Config.Mysql.Password,
        "tcp",
        Config.Mysql.Host,
        Config.Mysql.Port,
        Config.Mysql.Name,
        "utf8mb4",
    )
}

func Parse(configFile string) error {
    //判斷文件是否存在,如果不存在就返回錯誤
    if !file.IsExist(configFile) {
        return errors.New("config file " + configFile + " is not exist")
    }

    //讀取配置文件信息(讀取到的數據實際上是字符串),讀取失敗也會返回錯誤
    configContent, err := file.ToTrimString(configFile)
    if err != nil {
        return err
    }

    //使用YAML格式進行解析上一步讀取到的字符串。
    err = yaml.Unmarshal([]byte(configContent), &Config)
    if err != nil {
        return err
    }
    return nil
}

 

三.調用解析包

package main

import (
    "flag"
    "fmt"
    "log"
    "os"
    "yinzhengjie/springboardmachine/config"
)

func main() {
    /**
    flag的string方法源代碼如下:
        func String(name string, value string, usage string) *string {
            return CommandLine.String(name, value, usage)
        }
    下面是對flag的string方法進行解釋說明:
        name:
            指定自定義名稱,即用來標識該flag是用來干嘛的。
        value:
            指定默認值。
        usage:
            對當前的flag的一個描述信息
        *string:
            返回值是存儲標志值的字符串變量的地址(指針變量)。
     */
    configFile := flag.String("c", "/etc/springboardMchine/seelog.xml", "yaml config file")
    /*
    flag下面的這種寫法和上面的作用是一樣的,只不過上面的寫法更簡便,推薦大家使用上面的寫法

    var mode string
    flag.StringVar(&mode,"m", "client", "mode[client|server|jump|audit]")
    version := flag.Bool("v", false, "show version")
    */
    //開始進行解析,會將解析的結果復制給上述的configFile,version,mode這3個指針變量。
    flag.Parse()

    //判斷配置文件的長度
    if len(*configFile) == 0 {
        log.Println("not have config file.")
        os.Exit(0)
    }

    //解析配置文件
    err := config.Parse(*configFile)
    if err != nil {
        log.Println("parse config file error:", err)
        os.Exit(0)
    }

    //打印解析的參數
    fmt.Println(config.Config.Mysql.Host,config.Config.Mysql.Name,config.Config.Mysql.Port)
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM