Viper —— configuration solution for Go

1. support several formats of configuration

config.yaml

name: 'bobby'
port: 12334

main.go to quick start 

package main

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

type ServerConfig struct { 
    ServiceName string `mapstructure:"name"`    // using mapstructure to support other forms of config & using mapstructure pkg
    Port        int    `mapstructure:"port"`
}

func main() {
    v := viper.New() // return a Viper
    v.SetConfigFile("viper_test/ch01/config.yaml")
    //v.SetConfigFile("config.yaml")
    if err := v.ReadInConfig(); err != nil {
        panic(err)
    }
    sc := ServerConfig{}
    if err := v.Unmarshal(&sc); err != nil {  // unserilaize to Object
        panic(err)
    }
    fmt.Println(sc)
    fmt.Println(v.Get("name"))
}

2. nested yaml

name: 'bobby'
port: 12334
mysql:
    username: root
    password: root

main.go:

type ServerMysql struct {
    UserName string `mapstructure:"username"`
    PassWord string `mapstructure:"password"`
}

type ServerConfig struct {
    ServiceName string      `mapstructure:"name"`
    Port        int         `mapstructure:"port"`
    ServerMysql ServerMysql `mapstructure:"mysql"`
}

3. how to achieve the isolation of config between local and product env

本地运行时运行config_local.yaml文件: system environment 配置 MXSHOP_CONFIG_FLAG 为true

(配置了环境变量需要重启GOLAND)

生产运行config_pro.yaml

func GetSystemEnv(env string) bool {
    viper.AutomaticEnv()
    return viper.GetBool(env)  // can get sys env variable
}

func main() {
    flg := GetSystemEnv("MXSHOP_CONFIG_FLAG")
    filePrefix := "config"
    configFilePath := fmt.Sprintf("viper_test/ch02/%s_pro.yaml", filePrefix)
    if flg {
        configFilePath = fmt.Sprintf("viper_test/ch02/%s_local.yaml", filePrefix)
    }
    fmt.Println(configFilePath)
}

4. monitor changes in .yaml

    v.WatchConfig()
    v.OnConfigChange(func(e fsnotify.Event) {
        fmt.Println("config file changed")
        _ = v.ReadInConfig()
        _ = v.Unmarshal(&sc)
        fmt.Println(sc)
    })

 

posted @ 2023-11-03 20:42  PEAR2020  阅读(18)  评论(0)    收藏  举报