Use of go Viper package

Time:2022-5-27

viper

Viper is a complete go application configuration solution. It is designed to work in an application and can handle all types of configuration requirements and formats. It supports:

  • Support JSON, toml, yaml, HCl, envfile, Java and other rich configuration files
  • View and reread configuration files in real time (optional)
  • Read the data from the remote configuration system (etcd or consult) and observe the changes
  • Read from command line flags

The completed directory is as follows

.
├── config
│   ├── app.go //
│   └── config. Go // configuration file
├── go.mod
├── go.sum
├── main.go
└── pkg
    └── config
        └── config.go

use

Execute under your project directorygo mod init

 go get github.com/spf13/viper

newly buildpkg/configAnd createconfig.gofile

/**
  @author:panliang
  @data:2021/5/13
  @note
**/
package config

import (
    "github.com/spf13/cast"
    "github.com/spf13/viper"
    "log"
)

var Viper *viper.Viper

type StrMap map[string]interface{}

func init()  {
    Viper = viper.New()

    // 1.  Initialize Viper Library
    Viper = viper.New()
    // 2.  Set file name
    Viper.SetConfigName(".env")
    // 3.  Configuration type, supporting "JSON", "toml", "yaml", "YML", "properties",
    //             "props", "prop", "env", "dotenv"
    Viper.SetConfigType("env")
    // 4.  The path to find the environment variable configuration file, relative to main go
    Viper.AddConfigPath(".")

    // 5.  Start reading from the root directory Env file. If you can't read it, an error will be reported
    err := Viper.ReadInConfig()

    log.Println(err)

    // 6.  Set the environment variable prefix to distinguish the system environment variables of go
    Viper.SetEnvPrefix("appenv")
    // 7.  Viper. When get(), environment variables are read first
    Viper.AutomaticEnv()
}

//Env reads environment variables and supports default values
func Env(envName string, defaultValue ...interface{}) interface{} {
    if len(defaultValue) > 0 {
        return Get(envName, defaultValue[0])
    }
    return Get(envName)
}

//Add new configuration item
func Add(name string, configuration map[string]interface{}) {
    Viper.Set(name, configuration)
}

//Get gets the configuration item, and allows point acquisition, such as app name
func Get(path string, defaultValue ...interface{}) interface{} {
    //Non existent situation
    if !Viper.IsSet(path) {
        if len(defaultValue) > 0 {
            return defaultValue[0]
        }
        return nil
    }
    return Viper.Get(path)
}

//GetString get configuration information of string type
func GetString(path string, defaultValue ...interface{}) string {
    return cast.ToString(Get(path, defaultValue...))
}

//GetInt gets the configuration information of int type
func GetInt(path string, defaultValue ...interface{}) int {
    return cast.ToInt(Get(path, defaultValue...))
}

//Getint64 get configuration information of Int64 type
func GetInt64(path string, defaultValue ...interface{}) int64 {
    return cast.ToInt64(Get(path, defaultValue...))
}

//Getuint gets the configuration information of uint type
func GetUint(path string, defaultValue ...interface{}) uint {
    return cast.ToUint(Get(path, defaultValue...))
}

//Getbool get configuration information of bool type
func GetBool(path string, defaultValue ...interface{}) bool {
    return cast.ToBool(Get(path, defaultValue...))

}

establishconfigDirectory andapp.go

/**
  @author:panliang
  @data:2021/5/13
  @note
**/
package config

import "gotime/pkg/config"

func init() {
    config.Add("app", config.StrMap{
        //Application name, not used for the time being
        "name": config.Env("APP_NAME", "test"),

        //Current environment to distinguish multiple environments
        "env": config.Env("APP_ENV", "production"),
    })
}

Automatically read configuration creation under config directoryconfig.go

/**
  @author:panliang
  @data:2021/5/13
  @note
**/
package config

func Initialize() {
    //Trigger the init method of loading other files in this directory
}

newly buildmain.go

/**
  @author:panliang
  @data:2021/5/13
  @note
**/
package main

import (
    "fmt"
    "gotime/config"
    config2 "gotime/pkg/config"
)

func init()  {
    //Initialize load
    config.Initialize()
}

func main()  {
      //Print
    fmt.Println(config2.Get("app.name"))
}

New configuration.env

APP_NAME=tests
APP_ENV=local

implement

go run main.go

Use of go Viper package