简体   繁体   English

GoLang yaml 解组 - 更新结构

[英]GoLang yaml unmarshal - updating structs

I use https://github.com/go-yaml/yaml library to parse yaml settings file.我使用https://github.com/go-yaml/yaml库来解析 yaml 设置文件。 The settings struct needs to change slightly.设置结构需要稍微改变。

The current struct is当前结构是

type Settings struct{
   Hosts []string
}

The new struct should be新结构应该是

type Host struct {
   URL  string
   Name string
}
type Settings struct{
   Hosts []Host
}

Current yaml:当前 yaml:

hosts:
-http://server1.com
-http://server2.com

The new yaml will be新的 yaml 将

hosts:
- url:http://server1.com
  name:s1
- url:http://server2.com
  name:s2

I don't want to force users to go and update the yaml file after the change is implemented.我不想强迫用户使用 go 并在更改实施后更新 yaml 文件。 How can I parse both files (new and old)?如何解析两个文件(新旧)? For example, if the old file is received, I want name field to be empty.例如,如果收到旧文件,我希望名称字段为空。 If the new file is received then I will take whatever is provided.如果收到新文件,那么我将接受提供的任何内容。

Thanks!谢谢!

Correct way would be to release v2 of your package for new structure of Settings .正确的方法是发布您的 package v2以获得Settings的新结构。 Users of v2 can use new structure and existing users can keep using old structure with v1 of your package. v2 的用户可以使用新结构,现有用户可以继续使用 package v1 的旧结构。

If this is not possible then another way is to declare Settings as array of empty interface.如果这是不可能的,那么另一种方法是将设置声明为空接口数组。

type Settings struct{
   Hosts []interface{}
}

yaml will parse ok with this, and you will get data in Hosts fields as yaml 将解析 ok,您将在 Hosts 字段中获取数据

  1. array of string for old yaml旧 yaml 的string数组
  2. array of map[string]interface{} for new yaml新 yaml 的map[string]interface{}数组

type assertion will be needed to parse that into new struct or old struct.需要类型断言来将其解析为新结构或旧结构。

Note the type of Hosts will always be []interface{} , it is the elements whose type will need to be asserted to populate the fields.请注意,Hosts 的类型将始终为[]interface{} ,它是需要声明其类型以填充字段的元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM