golang中的配置管理库viper
阅读原文时间:2023年07月08日阅读:1

viper简介

Viper是适用于Go应用程序的完整配置解决方案。它旨在在应用程序中工作,并且可以处理所有类型的配置需求和格式。它支持:

设置默认值

从JSON,TOML,YAML,HCL,envfile和Java属性配置文件中读取

实时观看和重新读取配置文件(可选)

从环境变量中读取

从远程配置系统(etcd或Consul)中读取,并观察更改

从命令行标志读取

从缓冲区读取

设置显式值

可以将Viper视为满足您所有应用程序配置需求的注册表。

加载配置优先级

Viper会按照下面的优先级。每个项目的优先级都高于它下面的项目:

显示调用Set设置值

命令行参数(flag)

环境变量

配置文件

key/value存储

默认值

目录结构

config.yaml

db:
  username: mayanan
  password: 123456789
  host: 123.123.12.123
  port: 33066
  database: docker01
v: 88.88  # 将会覆盖: v.SetDefault("V", "1.11")  // 建立默认值
version: 99.99

config.go

package config

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

func LoadConfigFromYaml() (v *viper.Viper, err error) {
    v = viper.New()
    v.SetConfigName("config.yaml")
    v.AddConfigPath("./config/")
    v.SetConfigType("yaml")
    v.Set("version", "2.22")  // 显示调用Set设置值
    v.SetDefault("V", "1.11")  // 建立默认值

    // viper从环境变量读取
    v.SetEnvPrefix("spf")
    v.BindEnv("id")
    os.Setenv("spf_id", "111")

    if err = v.ReadInConfig(); err != nil {
        if _, ok := err.(viper.ConfigFileNotFoundError); ok {
            // Config file not found; ignore error if desired
            fmt.Println("Config file not found; ignore error if desired")
        } else {
            // Config file was found but another error was produced
            fmt.Println("Config file was found but another error was produced")
        }
    }

    // 监控配置和重新获取配置
    v.WatchConfig()

    v.OnConfigChange(func(e fsnotify.Event) {
        fmt.Println("Config file changed:", e.Name)
    })
    return v, err
}

main.go

package main

import (
    "fmt"
    "github.com/gin-gonic/gin"
    "viperTest/config"
)

func main() {
    router := gin.Default()
    v, _ := config.LoadConfigFromYaml()
    router.GET("/", func(context *gin.Context) {
        context.JSON(200, gin.H{
            "config": v.AllSettings(),
        })
        fmt.Println(v.GetString("db.password"), v.Get("id"))  // 获取单个配置属性
    })
    router.Run("127.0.0.1:8899")
}

获取值

在Viper中,根据值的类型,有几种获取值的方法。存在以下功能和方法:

Get(key string) : interface{}
GetBool(key string) : bool
GetFloat64(key string) : float64
GetInt(key string) : int
GetIntSlice(key string) : []int
GetString(key string) : string
GetStringMap(key string) : map[string]interface{}
GetStringMapString(key string) : map[string]string
GetStringSlice(key string) : []string
GetTime(key string) : time.Time
GetDuration(key string) : time.Duration
IsSet(key string) : bool
AllSettings() : map[string]interface{}

postman请求接口

http://127.0.0.1:8899

响应:

{
    "config": {
        "db": {
            "database": "docker01",
            "host": "123.123.12.123",
            "password": 123456,
            "port": 33066,
            "username": "mayanan"
        },
        "v": "1.11",
        "version": "2.22"
    }
}

此时把config.yaml中的内容改一下,再次请求接口,响应发生变化,根本不用重启我们的应用程序,非常的友好

写入配置文件

从配置文件中读取配置文件是有用的,但是有时你想要存储在运行时所做的所有修改。为此,可以使用下面一组命令,每个命令都有自己的用途:

WriteConfig - 将当前的viper配置写入预定义的路径并覆盖(如果存在的话)。如果没有预定义的路径,则报错。

SafeWriteConfig - 将当前的viper配置写入预定义的路径。如果没有预定义的路径,则报错。如果存在,将不会覆盖当前的配置文件。

WriteConfigAs - 将当前的viper配置写入给定的文件路径。将覆盖给定的文件(如果它存在的话)。

SafeWriteConfigAs - 将当前的viper配置写入给定的文件路径。不会覆盖给定的文件(如果它存在的话)。

根据经验,标记为safe的所有方法都不会覆盖任何文件,而是直接创建(如果不存在),而默认行为是创建或截断。

小示例:

viper.WriteConfig() // 将当前配置写入“viper.AddConfigPath()”和“viper.SetConfigName”设置的预定义路径
viper.SafeWriteConfig()
viper.WriteConfigAs("/path/to/my/.config")
viper.SafeWriteConfigAs("/path/to/my/.config") // 因为该配置文件写入过,所以会报错
viper.SafeWriteConfigAs("/path/to/my/.other_config")

viper中使用环境变量

Viper 完全支持环境变量。这使得12因素的应用程序开箱即用。有五种方法可以帮助与 ENV 合作:

AutomaticEnv()  // 可以通过v读取:v.Get("id")
BindEnv(string...) : error  // 绑定到viper中,既可以通过v读取,也可以通过v拿到配置
SetEnvPrefix(string)
SetEnvKeyReplacer(string...) *strings.Replacer
AllowEmptyEnv(bool)

viper简介

github.com/spf13/viper

手机扫一扫

移动阅读更方便

阿里云服务器
腾讯云服务器
七牛云服务器

你可能感兴趣的文章