golang模块viper读取配置文件

一、介绍

Viper是一个方便Go语言应用程序处理配置信息的库。它可以处理多种格式的配置。它支持的特性:

  • 设置默认值
  • 从JSON、TOML、YAML、HCL和Java properties文件中读取配置数据
  • 可以监视配置文件的变动、重新读取配置文件
  • 从环境变量中读取配置数据
  • 从远端配置系统中读取数据,并监视它们(比如etcd、Consul)
  • 从命令参数中读物配置
  • 从buffer中读取
  • 调用函数设置配置信息
简单的设置默认值
viper.SetDefault("time", "2019-7-14")
viper.SetDefault("notifyList", []string{"maple","ffm"})
监视配置文件,重新读取配置数据
package main

import (
    "fmt"
    "github.com/fsnotify/fsnotify"
    "github.com/spf13/viper"
)
viper:=viper.New()
viper.WatchConfig()
viper.OnConfigChange(func(e fsnotify.Event) {
  fmt.Println("Config file changed:", e.Name)
})

二、读取config.json

#json文件
{
  "appId": "123456789",
  "secret": "maple123456",
  "host": {
    "address": "localhost",
    "port": 5799
  }
}
package main

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

//定义config结构体
type Config struct {
    AppId string
    Secret string
    Host Host
}
//json中的嵌套对应结构体的嵌套
type Host struct {
    Address string
    Port int
}

func main() {
    config := viper.New()
    config.AddConfigPath("./kafka_demo")
    config.SetConfigName("config")
    config.SetConfigType("json")
    if err := config.ReadInConfig(); err != nil {
        panic(err)
    }
    fmt.Println(config.GetString("appId"))
    fmt.Println(config.GetString("secret"))
    fmt.Println(config.GetString("host.address"))
    fmt.Println(config.GetString("host.port"))

    //直接反序列化为Struct
    var configjson Config
    if err :=config.Unmarshal(&configjson);err !=nil{
        fmt.Println(err)
    }

    fmt.Println(configjson.Host)
    fmt.Println(configjson.AppId)
    fmt.Println(configjson.Secret)

}

 

转载于:https://www.cnblogs.com/angelyan/p/11185113.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值