douhu2131 2017-08-25 23:56
浏览 130
已采纳

Go中解析动态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

And here's my parsing code:

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.

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条回答 默认 最新

  • douqiao6563 2017-08-26 00:31
    关注

    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
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥15 绘制多分类任务的roc曲线时只画出了一类的roc,其它的auc显示为nan
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?