go-viper库-配置文件

项目地址

https://github.com/spf13/viper

支持的功能

  • 设置默认值

  • 从本地的JSON,TOML,YAML,HCL,环境变量文件,Java properties配置文件读取

  • 动态更新配置(修改本地配置文件时通知到程序)

  • 从环境变量读取

  • 从远端读取配置(如etcdconsul)并监视变化

  • 从命令行读取

  • Buffer读取

  • 显示的设置值

每种功能具体的用法README中有介绍

别人的博客

https://zhuanlan.zhihu.com/p/144323180

https://www.cnblogs.com/darjun/p/12216523.html

viper 的使用非常简单,它需要很少的设置。设置文件名(SetConfigName)、配置类型(SetConfigType)和搜索路径(AddConfigPath),然后调用ReadInConfig。 viper会自动根据类型来读取配置。使用时调用viper.Get方法获取键值。

有几点需要注意:

  • 设置文件名时不要带后缀;

  • 搜索路径可以设置多个,viper 会根据设置顺序依次查找;

  • viper 获取值时使用section.key的形式,即传入嵌套的键名;

  • 默认值可以调用viper.SetDefault设置。

viper 支持将配置Unmarshal到一个结构体中,为结构体中的对应字段赋值。

<pre class="md-fences md-end-block ty-contain-cm modeLoaded" spellcheck="false" lang="go" cid="n54" mdtype="fences" style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); font-size: 0.9em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(248, 248, 248); position: relative !important; border: 1px solid rgb(231, 234, 237); border-radius: 3px; padding: 8px 4px 6px; margin-bottom: 15px; margin-top: 15px; width: inherit; color: rgb(51, 51, 51); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial;">package main

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

type Name struct {
First string
Second string
}

type TestConfig struct {
Name Name
Age int
Hobbies string
}

func main() {
viper.SetConfigName("test_config")
viper.AddConfigPath(".")
viper.SetConfigType("json")

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

viper.ReadInConfig() // 读取配置文件: 这一步将配置文件变成了 Go语言的配置文件对象包含了 map,string 等对象。
fmt.Println(
viper.Get("name"), // 过去 配置文件的信息也很容易,用 Get方法。
viper.Get("age"),
viper.Get("name.first"),
viper.Get("hobbies"),
)

viper.ReadInConfig()
var c TestConfig
viper.Unmarshal(&c)
fmt.Println(c.Name, c.Age, c.Hobbies)
}
</pre>

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。