我有以下yml文件:
# config.yml
items:
name-of-item: # dynamic field
source: ...
destination: ...
我想用viper来解析它,但是name-of-item
可以是任何东西,所以我不知道如何解决这个问题。我知道我需要以下几点:
// inside config folder
package config
type Items struct {
NameOfItem NameOfItem
}
type NameOfItem struct {
Source string
Destination string
}
// inside main.go
package main
import (
"github.com/spf13/viper"
"log"
"github.com/username/lib/config"
)
func main() {
viper.SetConfigName("config.yml")
viper.AddConfigPath(".")
var configuration config.Item
if err := viper.ReadInConfig(); err != nil {
log.Fatalf("Error reading config file, %s", err)
}
err := viper.Unmarshal(&configuration)
if err != nil {
log.Fatalf("unable to decode into struct, %v", err)
}
}
在这种情况下,我可以解除封送,因为我声明了NameOfItem
,但是如果我不知道字段的名称(或者换句话说,如果它是动态的),我应该怎么办?
发布于 2018-09-08 16:41:40
Go中的struct
类型可能不是动态的(我怀疑它们在任何其他严格类型的语言中可能是动态的),所以您必须使用两个阶段的过程:
map[string]interface{}
类型的值。但是,从您的问题中还不清楚YAML数据是否真的是任意的,还是items
键包含一个统一的项数组--我的意思是,每个项都由source
和destination
值组成,只是不知道项本身的键。
在后一种情况下,items
块的解封送处理的目标应该是一个映射--类似于
type Item struct {
Source string
Destination string
}
items := make(map[string]Item)
err := viper.Unmarshal(items)
https://stackoverflow.com/questions/52230157
复制相似问题