viper应用案例1

2024-01-01  本文已影响0人  夜空最亮的9星

安装

    go get github.com/spf13/viper
    go get github.com/mitchellh/mapstructure

创建yaml文件

    v := viper.New()
    v.Set("key1", "value1")
    v.Set("key2", "value2")
    v.Set("key3", "value3")
    v.Set("key4", "value4")
    v.Set("key5", "value5")

    v.SetConfigFile("./config2")
    v.SetConfigType("yaml")
    v.WriteConfigAs("config2.yaml")

使用viper解析frpc.ini

frpc.ini

[common]
tls_enable = true
server_addr = serve.example.com
server_port = 3000

[server01]
type = tcp
local_ip = 127.0.0.1
local_port = 22
remote_port = 3926

首先定义结构体

type CommonVo struct {
    ServerAddr string `json:"server_addr" mapstructure:"server_addr"`
    ServerPort string `json:"server_port" mapstructure:"server_port"`
    TlsEnable  string `json:"tls_enable" mapstructure:"tls_enable"`
}
type ServerVo struct {
    Type       string `json:"type" mapstructure:"type"`
    LocalIp    string `json:"localIp" mapstructure:"local_ip"`
    LocalPort  string `json:"localPort" mapstructure:"local_port"`
    RemotePort string `json:"remotePort" mapstructure:"remote_port"`
}

编码

    viper.SetConfigFile("./frpc.ini")
    if err := viper.ReadInConfig(); err != nil {
        log.Fatal(err)
    }

    // 获取所有配置
    all := viper.AllSettings()
    fmt.Printf("size = %d\n", len(all))   // size = 2
    fmt.Printf("%#v\n", all)
    //map[string]interface {}{"common":map[string]interface {}{"server_addr":"serve.example.com", "server_port":"3000", "tls_enable":"true"}, "server01":map[string]interface {}{"local_ip":"127.0.0.1", "local_port":"22", "remote_port":"3926", "type":"tcp"}}


    keys := viper.AllKeys()

    for i, k := range keys {
        fmt.Printf("%d  === %s \n", i, k)
    }
    
    //  0  === server01.remote_port 
    //  1  === common.server_port 
    //  2  === common.tls_enable 
    //  3  === common.server_addr 
    //  4  === server01.type 
    //  5  === server01.local_ip 
    //  6  === server01.local_port 

    for i, k := range all {
        fmt.Printf("%s  === %s \n", i, k)
    }
    //  server01  === map[local_ip:127.0.0.1 local_port:22 remote_port:3926 type:tcp] 
    //  common  === map[server_addr:serve.example.com server_port:3000 tls_enable:true] 
    
    stringMap := viper.GetStringMap("common")
    
    fmt.Printf("%#v\n", stringMap)
    //map[string]interface {}{"server_addr":"serve.example.com", "server_port":"3000", "tls_enable":"true"}


    for i, k := range all {

        if i == "common" {
            var cInfo CommonVo
            mapstructure.Decode(k, &cInfo)
            fmt.Println("")
            fmt.Printf("%#v", cInfo)
            //test.CommonVo{ServerAddr:"serve.example.com", ServerPort:"3000", TlsEnable:"true"}--- PASS: Test_viper2 (0.00s)

        } else {
            demo := ServerVo{}
            mapstructure.Decode(k, &demo)
            fmt.Println("")
            fmt.Printf("%#v", demo)
            //test.ServerVo{Type:"tcp", LocalIp:"127.0.0.1", LocalPort:"22", RemotePort:"3926"}

        }
        
            //新增属性
            viper.Set("user_id", "123456789")
            
            //监听文件变化
            viper.WatchConfig()
            viper.OnConfigChange(func(e fsnotify.Event) {
                fmt.Println("config file changed:", e.Name)
        
            })
            //保存到文件
            viper.WriteConfigAs("frpc.ini")

    }
    

viper 读取json

tmp.json

{
  "date": "2019-04-30",
  "mysql": {
    "url": "127.0.0.1:3306",
    "username": "root",
    "password": "123456"
  }
}

    viper.SetConfigName("tmp") //设置配置文件的名字
    viper.AddConfigPath(".")    //添加配置文件所在的路径
    viper.SetConfigType("json") //设置配置文件类型,可选
    err := viper.ReadInConfig()
    if err != nil {
        fmt.Printf("config file error: %s\n", err)
        os.Exit(1)
    }
    urlValue := viper.Get("mysql.url")
    fmt.Println("mysql url:", urlValue)
    fmt.Printf("mysql url: %s\n mysql username: %s\n mysql password: %s", viper.Get("mysql.url"), viper.Get("mysql.username"), viper.Get("mysql.password"))

从io.Reader读取配置

    viper.SetConfigType("yaml") // 或者 viper.SetConfigType("YAML")

    // 任何需要将此配置添加到程序中的方法。
    var yamlExample = []byte(`
Hacker: true
name: steve
hobbies:
- skateboarding
- snowboarding
- go
clothing:
  jacket: leather
  trousers: denim
age: 35
eyes : brown
beard: true
`)

    viper.ReadConfig(bytes.NewBuffer(yamlExample))

    name := viper.Get("name") // 这里会得到 "steve"s
    fmt.Println(name)
    viper.WriteConfigAs("config2.yaml")

注册和使用别名

注册和使用别名

别名允许多个键引用单个值

viper.RegisterAlias("loud", "Verbose")  // 注册别名(此处loud和Verbose建立了别名)

viper.Set("verbose", true) // 结果与下一行相同
viper.Set("loud", true)   // 结果与前一行相同

viper.GetBool("loud") // true
viper.GetBool("verbose") // true

更多参考

https://zhuanlan.zhihu.com/p/272508571
https://juejin.cn/post/7229480315353514045

上一篇 下一篇

猜你喜欢

热点阅读