我正在将一个Yaml配置文件解组到Golang struct。我想实现以下逻辑:

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("%+v\n", configWithBlacklistValues)
    fmt.Printf("%+v\n", configWithoutBlacklistValues)
    fmt.Printf("%+v\n", 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
    */
}

使用list作为指针类型的代码采样。https://play.golang.org/p/wK8i3dLCHWQ

type HostList []string

type Config struct {
    Host string `yaml:"host"`
    Blacklist *HostList `yaml:"blacklist"`
}