Go中解析动态YAML的惯用方式是什么? [英] What's the idiomatic way of parsing dynamic YAML in Go?

查看:53
本文介绍了Go中解析动态YAML的惯用方式是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些用于处理YAML配置文件的代码,该文件带有类型断言有些失控了,我觉得必须有更好的方法来做到这一点.

I have some code for handling a YAML config file that's getting a little out-of-control w/ type assertions and I feel like there must be a better way to do this.

以下是我的配置文件中的相关代码段:

Here's the relevant snippet from my config file:

plugins:
  taxii20:
    default: default
    api_roots:
      default:
        auth:
          - ldap
          - mutualtls
        collections:
          all:
            selector: g.V().Save("<type>").Save("<created>").All()
            selector_query_lang: gizmo

这是我的解析代码:

func parseTaxiiConfig() {
    plg.ConfigMutex.Lock()
    taxiiConfig := plg.ConfigData.Plugins["taxii20"].(map[interface{}]interface{})
    ConfigData = &Config{}
    if taxiiConfig["default"] != nil {
        ConfigData.DefaultRoot = taxiiConfig["default"].(string)
    }
    if taxiiConfig["api_roots"] != nil {
        ConfigData.APIRoots = make([]model.APIRoot, 0)
        iroots := taxiiConfig["api_roots"].(map[interface{}]interface{})
        for iname, iroot := range iroots {
            root := model.APIRoot{Name: iname.(string)}
            authMethods := iroot.(map[interface{}]interface{})["auth"].([]interface{})
            root.AuthMethods = make([]string, 0)
            for _, method := range authMethods {
                root.AuthMethods = append(root.AuthMethods, method.(string))
            }
            collections := iroot.(map[interface{}]interface{})["collections"].(map[interface{}]interface{})
            root.Collections = make([]model.Collection, 0)
            for icolName, icollection := range collections {
                collection := model.Collection{Name: icolName.(string)}
                collection.Selector = icollection.(map[interface{}]interface{})["selector"].(string)
                collection.SelectorQueryLang = icollection.(map[interface{}]interface{})["selector_query_lang"].(string)
                root.Collections = append(root.Collections, collection)
            }
            ConfigData.APIRoots = append(ConfigData.APIRoots, root)
        }
    }
    plg.ConfigMutex.Unlock()

    // debug
    fmt.Println(ConfigData)
}

代码按预期工作,但是这里有太多类型断言,我无法撼动自己缺少更好方法的感觉.

The code works as intended, but there's just so many type assertions here and I can't shake the feeling that I'm missing a better way.

正如配置所暗示的那样,可能要注意的一个关键项目是Caddy风格的插件系统的配置,因此主配置解析器无法提前知道插件配置的形状.它必须将对配置文件的插件部分的处理委托给插件本身.

One possible critical item of note, as the config implies, this is configuration for a Caddy-style plugin system, so the main config parser cannot know ahead of time what the shape of the plugin config will look like. It has to delegate processing of the plugin's portion of the config file to the plugin itself.

推荐答案

这是我想出的.更具可读性.

Here's what I came up with instead. Much more readable.

// Config represents TAXII 2.0 plugin structure
type Config struct {
    DefaultRoot string
    APIRoots    []model.APIRoot
}

// Intermediate config for mapstructure
type configRaw struct {
    DefaultRoot string                `mapstructure:"default"`
    APIRoots    map[string]apiRootRaw `mapstructure:"api_roots"`
}
type apiRootRaw struct {
    AuthMethods []string                 `mapstructure:"auth"`
    Collections map[string]collectionRaw `mapstructure:"collections"`
}
type collectionRaw struct {
    Selector          string `mapstructure:"selector"`
    SelectorQueryLang string `mapstructure:"selector_query_lang"`
}

func parseTaxiiConfig() error {
    plg.ConfigMutex.Lock()
    defer plg.ConfigMutex.Unlock()

    taxiiConfig := plg.ConfigData.Plugins["taxii20"].(map[interface{}]interface{})
    fmt.Println(taxiiConfig)
    ConfigData = &Config{}
    raw := &configRaw{}
    err := mapstructure.Decode(taxiiConfig, raw)
    if err != nil {
        return err
    }

    ConfigData.DefaultRoot = raw.DefaultRoot
    ConfigData.APIRoots = make([]model.APIRoot, 0)
    for name, root := range raw.APIRoots {
        apiRoot := model.APIRoot{Name: name}
        apiRoot.AuthMethods = root.AuthMethods
        apiRoot.Collections = make([]model.Collection, 0)
        for colName, col := range root.Collections {
            collection := model.Collection{Name: colName}
            collection.Selector = col.Selector
            collection.SelectorQueryLang = col.SelectorQueryLang
            apiRoot.Collections = append(apiRoot.Collections, collection)
        }
        ConfigData.APIRoots = append(ConfigData.APIRoots, apiRoot)
    }

    return nil
}

这篇关于Go中解析动态YAML的惯用方式是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆