区分"No Key"和"No Values",同时将 Yaml 列表反序列化/解组为 Golang 结构



我正在将一个Yaml配置文件解组为Golang结构体。我想实现以下逻辑:

if blacklist key is not there in yaml:
then allow everything
else if blacklist key is there but there are no values:
then block everything
else if blacklist values are there in yaml:
then filter out only the listed items

我不能区分最后两种情况。本质上两者看起来是一样的,即"黑名单键"没有值。但我想知道有没有可能。(没有在yaml中引入任何额外的标志)。我尝试了指针类型,但它不起作用。下面是简化的代码示例:https://play.golang.org/p/UheBEPFhzsg

package main
import (
"fmt"
"gopkg.in/yaml.v2"
)
type Config struct {
Host string        `yaml:"host"`
Blacklist []string `yaml:"blacklist"`
}
func main() {
configDataWithBlacklistValues := `
host: localhost
blacklist: 
- try
- experiment
`
configDataWithoutBlacklistValues := `
host: localhost
blacklist:
`
configDataWithoutBlacklistKey := `
host: localhost
`
var configWithBlacklistValues Config    // this config should filter out blacklist items
var configWithoutBlacklistValues Config // this config should filter out everything (no blacklist values = everything to blacklist)
var configWithoutBlacklistKey Config    // this config should filter out nothing (no blacklist key = nothing to blacklist)
yaml.Unmarshal(([]byte)(configDataWithBlacklistValues), &configWithBlacklistValues)
yaml.Unmarshal(([]byte)(configDataWithoutBlacklistValues), &configWithoutBlacklistValues)
yaml.Unmarshal(([]byte)(configDataWithoutBlacklistKey), &configWithoutBlacklistKey)
fmt.Printf("%+vn", configWithBlacklistValues)
fmt.Printf("%+vn", configWithoutBlacklistValues)
fmt.Printf("%+vn", configWithoutBlacklistKey)

/*
if blacklist key is not there in yaml:
then allow everything
else if blacklist key is there but there are no values:
then block everything
else if blacklist values are there in yaml:
then filter out only the listed items
*/
}
用列表作为指针类型的代码示例。https://play.golang.org/p/wK8i3dLCHWQ
type HostList []string
type Config struct {
Host string `yaml:"host"`
Blacklist *HostList `yaml:"blacklist"`
}

一个简单的解决方案是实现指针类型HostList,但编码2)case YAML,即没有黑名单值的数据,如下所示

host: localhost
blacklist: []

通过这样做,您的反编组将返回零长度片([]string{})而不是nil片。因此,您的代码可以检查nil切片,仅为第三种情况。

去操场

最新更新