golang模塊viper讀取配置文件


一、介紹

Viper是一個方便Go語言應用程序處理配置信息的庫。它可以處理多種格式的配置。它支持的特性:

  • 設置默認值
  • 從JSON、TOML、YAML、HCL和Java properties文件中讀取配置數據
  • 可以監視配置文件的變動、重新讀取配置文件
  • 從環境變量中讀取配置數據
  • 從遠端配置系統中讀取數據,並監視它們(比如etcd、Consul)
  • 從命令參數中讀物配置
  • 從buffer中讀取
  • 調用函數設置配置信息

簡單的設置默認值

viper.SetDefault("time", "2019-7-14")
viper.SetDefault("notifyList", []string{"maple","ffm"})

監視配置文件,重新讀取配置數據

package main

import (
    "fmt"
    "github.com/fsnotify/fsnotify"
    "github.com/spf13/viper"
)
viper:=viper.New()
viper.WatchConfig()
viper.OnConfigChange(func(e fsnotify.Event) {
  fmt.Println("Config file changed:", e.Name)
})

二、讀取config.json

#json文件
{
  "appId": "123456789",
  "secret": "maple123456",
  "host": {
    "address": "localhost",
    "port": 5799
  }
}
package main

import (
    "fmt"
    "github.com/spf13/viper"
)

//定義config結構體
type Config struct {
    AppId string
    Secret string
    Host Host
}
//json中的嵌套對應結構體的嵌套
type Host struct {
    Address string
    Port int
}

func main() {
    config := viper.New()
    config.AddConfigPath("./kafka_demo")
    config.SetConfigName("config")
    config.SetConfigType("json")
    if err := config.ReadInConfig(); err != nil {
        panic(err)
    }
    fmt.Println(config.GetString("appId"))
    fmt.Println(config.GetString("secret"))
    fmt.Println(config.GetString("host.address"))
    fmt.Println(config.GetString("host.port"))

    //直接反序列化為Struct
    var configjson Config
    if err :=config.Unmarshal(&configjson);err !=nil{
        fmt.Println(err)
    }

    fmt.Println(configjson.Host)
    fmt.Println(configjson.AppId)
    fmt.Println(configjson.Secret)

}

 


免責聲明!

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



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