我正在尝试使用viper库读取 json 文件中的配置
//config.json
{
"currency": {
"btc": [{
"api_endpoint": "api.blockcypher.com/v1/btc/main/addrs/$address/balance",
"balance_threshold": 234234.34,
"wallet_address": "0xsdrsdf",
"alerts":{
"slack": "put slack config here",
"sms": "put sms config here"
},
"enable_monitoring": true
}],
"eth": [{
"api_endpoint": "some endpoint",
"balance_threshold" : 2234234.234,
"wallet_address": "0xsdrsdf",
"alerts":{
"slack": "put slack config here",
"sms": "put sms config here"
},
"enable_monitoring": true
}]
}
}
和 config.go 像这样
func GetConfig() {
viper.SetConfigName("config") // name of config file (without extension)
viper.SetConfigType("json") // REQUIRED if the config file does not have the extension in the name
viper.AddConfigPath(".") // path to look for the config file in
viper.AddConfigPath("$HOME/") // path to look for the config file in
err := viper.ReadInConfig() // Find and read the config file
if err != nil { // Handle errors reading the config file
panic(fmt.Errorf("Fatal error config file: %s", err))
}
var config config
viper.Unmarshal(&config)
fmt.Println(viper.Get("currency"))
fmt.Printf("Config: %v\n", config["currency"])
}
type coreconfig struct {
APIEndpoint string `json:"api_endpoint"`
BalanceThreshold float64 `json:"balance_threshold"`
WalletAddress string `json:"wallet_address"`
EnableMonitoring bool `json:"enable_monitoring"`
Alerts map[string]alerts
}
type alerts struct {
Sms string `json:"sms"`
Slack string `json:"slack"`
}
type currencyconfig map[string][]coreconfig
type config map[string]currencyconfig
输出打印为空配置
[map[btc:[map[alerts:[map[slack:put slack config here sms:put sms config here]] api_endpoint:api.blockcypher.com/v1/btc/main/addrs/$address/balance balance_threshold:234234 enable_monitoring:true wallet_address:0xsdrsdf]] eth:[map[alerts:[map[slack:put slack config here sms:put sms config here]] api_endpoint:some endpoint balance_threshold:2.234234e+06 enable_monitoring:true wallet_address:0xsdrsdf]]]] <= This shows that config file is read correctly
Config: map[] <= actual output