在Go语言中,解析动态YAML的惯用方式是什么?

huangapple go评论177阅读模式
英文:

What's the idiomatic way of parsing dynamic YAML in Go?

问题

我有一些处理YAML配置文件的代码,但是类型断言有点混乱,我觉得一定有更好的方法来处理这个问题。

这是我配置文件中相关的代码片段:

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)
}

代码的功能是正常的,但是这里有太多的类型断言,我感觉可能有更好的方法。

一个可能需要注意的关键点是,正如配置文件所示,这是一个Caddy风格的插件系统的配置,所以主配置解析器无法预先知道插件配置的形状。它必须将插件自身的配置文件处理委托给插件本身。

英文:

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(&quot;&lt;type&gt;&quot;).Save(&quot;&lt;created&gt;&quot;).All()
            selector_query_lang: gizmo

And here's my parsing code:

func parseTaxiiConfig() {
	plg.ConfigMutex.Lock()
	taxiiConfig := plg.ConfigData.Plugins[&quot;taxii20&quot;].(map[interface{}]interface{})
	ConfigData = &amp;Config{}
	if taxiiConfig[&quot;default&quot;] != nil {
		ConfigData.DefaultRoot = taxiiConfig[&quot;default&quot;].(string)
	}
	if taxiiConfig[&quot;api_roots&quot;] != nil {
		ConfigData.APIRoots = make([]model.APIRoot, 0)
		iroots := taxiiConfig[&quot;api_roots&quot;].(map[interface{}]interface{})
		for iname, iroot := range iroots {
			root := model.APIRoot{Name: iname.(string)}
			authMethods := iroot.(map[interface{}]interface{})[&quot;auth&quot;].([]interface{})
			root.AuthMethods = make([]string, 0)
			for _, method := range authMethods {
				root.AuthMethods = append(root.AuthMethods, method.(string))
			}
			collections := iroot.(map[interface{}]interface{})[&quot;collections&quot;].(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{})[&quot;selector&quot;].(string)
				collection.SelectorQueryLang = icollection.(map[interface{}]interface{})[&quot;selector_query_lang&quot;].(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.

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.

答案1

得分: 0

这是我改写后的代码,更易读。

// Config 表示TAXII 2.0插件结构
type Config struct {
	DefaultRoot string
	APIRoots    []model.APIRoot
}

// 用于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
}
英文:

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:&quot;default&quot;`
APIRoots    map[string]apiRootRaw `mapstructure:&quot;api_roots&quot;`
}
type apiRootRaw struct {
AuthMethods []string                 `mapstructure:&quot;auth&quot;`
Collections map[string]collectionRaw `mapstructure:&quot;collections&quot;`
}
type collectionRaw struct {
Selector          string `mapstructure:&quot;selector&quot;`
SelectorQueryLang string `mapstructure:&quot;selector_query_lang&quot;`
}
func parseTaxiiConfig() error {
plg.ConfigMutex.Lock()
defer plg.ConfigMutex.Unlock()
taxiiConfig := plg.ConfigData.Plugins[&quot;taxii20&quot;].(map[interface{}]interface{})
fmt.Println(taxiiConfig)
ConfigData = &amp;Config{}
raw := &amp;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
}

huangapple
  • 本文由 发表于 2017年8月26日 07:56:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/45890716.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定