登录
首页 >  Golang >  Go问答

将 Yaml 列表反序列化/解组到 Golang 结构时区分“无键”和“无值”

来源:stackoverflow

时间:2024-04-02 09:48:36 199浏览 收藏

本篇文章给大家分享《将 Yaml 列表反序列化/解组到 Golang 结构时区分“无键”和“无值”》,覆盖了Golang的常见基础知识,其实一个语言的全部知识点一篇文章是不可能说完的,但希望通过这些问题,让读者对自己的掌握程度有一定的认识(B 数),从而弥补自己的不足,更好的掌握它。

问题内容

我正在将 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("%+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
    */
}

使用列表作为指针类型的代码示例。 https://play.golang.org/p/wk8i3dlchwq

type HostList []string

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

正确答案


解决方案的一个简单解决方法是实现指针类型 hostlist,但对 2) 情况 yaml 进行编码,即没有黑名单值的数据,如下所示

host: localhost
blacklist: []

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

Go Playground

到这里,我们也就讲完了《将 Yaml 列表反序列化/解组到 Golang 结构时区分“无键”和“无值”》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>