go配置包-viper

config.json

{
    "logCfg": {
        "type": 0
    },
    "scanCfg": {
        "suffix": [ // suffix是数组
            "txt",
            "log"
        ],
        "type": [
            "img"
        ]
    }
}

config.go

package config

import (
	"fmt"

	"github.com/spf13/viper"
)

/** 配置 */
type Cfg struct {
	LogCfg  LogCfg  `json:"logCfg"`
	ScanCfg ScanCfg `json:"scanCfg"`
}

/** LogCfg 日志配置 */
type LogCfg struct {
	Type int `json:"type"` /** 记录类型;0.命令行和文件,1.只记录到文件,2.只命令行输出 */
}

/** ScanCfg 扫描文件配置 */
type ScanCfg struct {
	Suffix []string `json:"suffix"` /** 忽略指定后缀 */
	Type   []string `json:"type"`   /** 忽略指定的mime类型 */
}

const configFile = "config.json"

var SerCfg Cfg

func init() {
	v := viper.New()
	v.SetDefault("LogCfg.Type", 0)
	v.SetDefault("ScanCfg.Suffix", []string{"log", "txt"}) // 设置默认值
	v.SetDefault("ScanCfg.Type", []string{"png", "jpg"})
	v.SetConfigFile(configFile)
	err := v.ReadInConfig()
	if err != nil {
		panic(fmt.Errorf("Fatal error config file: %s \n", err))
	}

	if err := v.Unmarshal(&SerCfg); err != nil {
		fmt.Println(err)
	}
	// 就可以SerCfg.ScanCfg.Suffix来访问了
}


package main

import (
	"fmt"
	"github.com/fsnotify/fsnotify"
	"github.com/spf13/viper"
)
//https://www.cnblogs.com/kainhuck/p/13288512.html
//https://studygolang.com/articles/35030?fr=sidebar
func main(){
	//viper.SetConfigName("sss") // name of config file (without extension)
	//viper.SetConfigType("json") // REQUIRED if the config file does not have the extension in the name
	//viper.AddConfigPath("config/")   // path to look for the config file in
	viper.SetConfigFile("config/sss.json")

	//viper.ReadRemoteConfig()
	//viper.ReadConfig()
	if err := viper.ReadInConfig(); err != nil {
		if _, ok := err.(viper.ConfigFileNotFoundError); ok {
			panic(fmt.Errorf("ConfigFileNotFoundError: %s \n", err))
		} else {
			panic(fmt.Errorf("ConfigError: %s \n", err))
		}
	}

	viper.SetConfigFile("config/dev.json")
	viper.MergeInConfig() // 合并前面的config,如果有相同的配置,那么这里会替换前面的

	viper.WatchConfig()  // 只会监听最后一个文件的更改
	viper.OnConfigChange(func(e fsnotify.Event) {
		fmt.Println("Config file changed:", e.Name)
		fmt.Println("exists",viper.IsSet("dev"),viper.GetBool("dev"))
		fmt.Println("exists_str",viper.IsSet("str"),viper.GetString("str"))
	})

	fmt.Println("exists",viper.IsSet("dev"),viper.GetBool("dev"))

	c := viper.Get("config.Endpoint") // viper.GetString("key")
	fmt.Println(c,"v")

	boo := viper.Get("dev")
	if boo == nil{
		fmt.Println(boo,"nil","boo")
	}else{
		fmt.Println(boo)
	}

	fmt.Println("str",viper.IsSet("str"),viper.GetString("str"))
	select{}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值