中使用动态键解析

中使用动态键解析

本文介绍了如何在 Golang 中使用动态键解析 YAML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Go 解析 YAML 文件.问题是 YAML 文件中的键可能并不总是相同的.这是为了进行 API 版本控制,以便用户可以定义他们支持的版本.例如 V1、V2、V3 等.它们不需要按顺序排列,可以省略它们不支持的版本,即 V0、V2、V5 等.

I am trying to parse a YAML file with Go. The problem is that the keys in the YAML file might not always be the same. This is to do API versioning so the user can define the versions they support. For instance V1, V2, V3 etc. They do not need to be in order and can omit versions they don't support i.e, V0, V2, V5 etc.

package main

import (
  "fmt"
  "gopkg.in/yaml.v2"
)

var data = `
---
development:
  skip-header-validation: true
  V1:
    current: "1.0.0"
    mime_types:
      - application/vnd.company.jk.identity+json;
      - application/vnd.company.jk.user+json;
      - application/vnd.company.jk.role+json;
      - application/vnd.company.jk.scope+json;
      - application/vnd.company.jk.test+json;
    skip-mime-type-validation: true
    skip-version-validation: true
  V2:
    current: "2.0.0"
    mime_types:
      - application/vnd.company.jk.identity+json;
      - application/vnd.company.jk.user+json;
      - application/vnd.company.jk.role+json;
      - application/vnd.company.jk.scope+json;
      - application/vnd.company.jk.test+json;

`

type MajorVersion struct {
  Current                 string    `yaml:"current"`
  MimeTypes               []string  `yaml:"mime_types"`
  SkipVersionValidation   bool      `yaml:"skip-version-validation"`
  SkipMimeTypeValidation  bool      `yaml:"skip-mime-type-validation"`
}

type Environment struct {
  SkipHeaderValidation  bool        `yaml:"skip-header-validation"`
  Version               map[string]MajorVersion
}

func main() {
  e := Environment{}

  yaml.Unmarshal([]byte(data), &e)
  fmt.Println(e)
}

我看到了一个在这里提出的类似问题

这是在顶层,我还没有完全弄清楚如何从结构内部做到这一点.

This is at the top level and I haven't quite figured out how to do this from inside the struct.

推荐答案

首先,您尝试将根解析为 Environment,但它的实际类型是 map[string]Environment.其次,您将需要一个自定义 Unmarshaler 如果您想保留该类型结构.像这样的:

First, you are trying to parse the root as an Environment, but its actual type is map[string]Environment. Second, you are going to need a custom Unmarshaler if you want to keep that type structure. Something like this:

package main

import (
    "fmt"

    "gopkg.in/yaml.v2"
)

var data = `
---
development:
  skip-header-validation: true
  V1:
    current: "1.0.0"
    mime_types:
      - application/vnd.company.jk.identity+json;
      - application/vnd.company.jk.user+json;
      - application/vnd.company.jk.role+json;
      - application/vnd.company.jk.scope+json;
      - application/vnd.company.jk.test+json;
    skip-mime-type-validation: true
    skip-version-validation: true
  V2:
    current: "2.0.0"
    mime_types:
      - application/vnd.company.jk.identity+json;
      - application/vnd.company.jk.user+json;
      - application/vnd.company.jk.role+json;
      - application/vnd.company.jk.scope+json;
      - application/vnd.company.jk.test+json;

`

type MajorVersion struct {
    Current                string   `yaml:"current"`
    MimeTypes              []string `yaml:"mime_types"`
    SkipVersionValidation  bool     `yaml:"skip-version-validation"`
    SkipMimeTypeValidation bool     `yaml:"skip-mime-type-validation"`
}

type Environment struct {
    SkipHeaderValidation bool
    Versions             map[string]MajorVersion
}

func (e *Environment) UnmarshalYAML(unmarshal func(interface{}) error) error {
    var params struct {
        SkipHeaderValidation bool `yaml:"skip-header-validation"`
    }
    if err := unmarshal(&params); err != nil {
        return err
    }
    var versions map[string]MajorVersion
    if err := unmarshal(&versions); err != nil {
        // Here we expect an error because a boolean cannot be converted to a
        // a MajorVersion
        if _, ok := err.(*yaml.TypeError); !ok {
            return err
        }
    }
    e.SkipHeaderValidation = params.SkipHeaderValidation
    e.Versions = versions
    return nil
}

func main() {
    var e map[string]Environment
    if err := yaml.Unmarshal([]byte(data), &e); err != nil {
        fmt.Println(err.Error())
    }
    fmt.Printf("%#v
", e)
}

输出(使用化妆后):

map[string]main.Environment{
    "development": {
        SkipHeaderValidation: true,
        Versions:             {
            "V2": {
                Current:                "2.0.0",
                MimeTypes:              {"application/vnd.company.jk.identity+json;", "application/vnd.company.jk.user+json;", "application/vnd.company.jk.role+json;", "application/vnd.company.jk.scope+json;", "application/vnd.company.jk.test+json;"},
                SkipVersionValidation:  false,
                SkipMimeTypeValidation: false,
            },
            "V1": {
                Current:                "1.0.0",
                MimeTypes:              {"application/vnd.company.jk.identity+json;", "application/vnd.company.jk.user+json;", "application/vnd.company.jk.role+json;", "application/vnd.company.jk.scope+json;", "application/vnd.company.jk.test+json;"},
                SkipVersionValidation:  true,
                SkipMimeTypeValidation: true,
            },
        },
    },
}

这篇关于如何在 Golang 中使用动态键解析 YAML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 05:35