Go viper 配置文件读取工具

时间:2022-07-23
本文章向大家介绍Go viper 配置文件读取工具,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

安装

    go get github.com/spf13/viper

简单例子

/*
  目录
    - main.go
    - config.yaml
*/



func main(){
    
    
    viper.SetConfigName("config") // 设置配置名称
    viper.SetConfigFile("config.yaml") // 设置配置文件路径
    
    // 读取配置
    if err := viper.ReadInConfig(); err != nil{
        log.Fatal(err)
    }
    
    // 获取配置数据
    summary := viper.GetString("Summary")

    fmt.Println(summary)
        
}

新建 Viper

viper 提供默认 Viper对象, 可直接使用。 也通过 New 方法创建自定义Viper

// 直接使用默认对象
viper.GetInt("count")

// 获取全局Viper对象
globalViper := viper.GetViper()

// 新建Viper
conf := viper.New()

conf.SetConfigFile("config.yaml")

读取配置文件

从配置读取

 viper.SetConfigName("config")
 viper.SetConfigFile("config.yaml")
 
 if err := viper.ReadInConfig(); err != nil{
     log.Fatal(err)
 }
 
 version := viper.GetString("version")

从 io.Reader 读取

func main(){
    
    file, err := os.Open("./config.yaml")
    
    if err != nil{
        log.Fatal(err)
    }
    
    defer file.Close()
    
    viper.SetConfig("yaml")
    
    version := viper.GetString("version")
    // 这里需要设置配置类型, 否则无法正确解释配置内容
    
    // 如果未配置类型,也可以通过 Get 方法获取数据自行解析。
    
    
    
}

从 flag 读取

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

func main() {
    pflag.String("ip", "127.0.0.1", "Server running address")
    pflag.Int64("port", 8080, "Server running port")
    pflag.Parse()

    viper.BindPFlags(pflag.CommandLine)
    fmt.Printf("ip :%s , port:%s", viper.GetString("ip"), viper.GetString("port"))


}

获取值

值得获取方法名为 Get[type] 形式

  • 接口类型,既未作解析
    • Get
  • 布尔
    • GetBool
  • 时间
    • GetDuration
    • GetTime
  • 数字
    • GetInt
    • GetInt32
    • GetInt64
    • GetFloat64
    • GetIntSlice
    • ....
  • 字符
    • GetString
    • GetStringSlice
    • ....

设置默认值

setDefault

 viper.setConfigFile("config.yaml")
 viper.SetDefault("port", 8000)
    
 println(viper.GetInt("port") // 8000
 // 这里未读取配置文件,将返回默认值

将配置映射到结构体

  • Unmarshal 将配置属性映射到 struct 中, 匹配模式类似 JSON 解析,只匹配大写开头的属性
type User struct{
    ID string
    Name string
    nickName string // 小写属性将不做匹配
}

func main(){
    
    /* config.yaml
        
        id: id11
        name: Rogan
        nickName: "wolf"  
    
    */
    ...
    
    user := &User{}
    
    viper.Unmarshal(user)
    
    println(&user) // { id11, Rogan } 
    
    
}
  • UnmarshalExact 用法与 Unmarshal 相同, 不同的是struct 必须与配置属性完全匹配,否则加报错
 /*
  config.yaml
  
    id: 111
    name: Rogan
 
 */
 
 type Conf_1 struct{
     Id string
     Name string
 }
 
 // 将报错
 type Conf_2 struct{
     Id string
 }
  • UnmarshalKey 匹配某一字段
 /*
  config.yaml
  
    server: 
        port: 8000
        host: localhost
 
 */

type ServerConf struct{
    Port int
    host string
}

func main(){
    
    ...
    
    serverConf := &ServerConf{}
    
    viper.UnmarshalKey("server", serverConfig)
    
}

混合配置 Merge[type]

  • MergeConfig
func main(){


    viper.SetConfigName("config")
    viper.SetConfigFile("config.yaml")

    viper.ReadInConfig()
    
    
    log.Println(viper.GetString("Summary"), viper.InConfig("Summary"))
    
    buff := []byte(`Name: jeck`)

    viper.MergeConfig(bytes.NewReader(buff))

    log.Println(viper.GetString("Name"))
    
}

监听文件

  • WatchConfig
func main(){

    viper.SetConfigName("config")
    viper.SetConfigFile("config.yaml")

    viper.ReadInConfig()

    viper.WatchConfig()

    for {

        log.Println(viper.GetString("version"))

        time.Sleep(time.Second * 5)

    }
    
    
}

// 初始 versioni: 1
// --> 1
// 修改config.yaml version: 2
// --> 2
  • OnConfigChange 响应配置变化