I use https://github.com/go-yaml/yaml library to parse yaml settings file. 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:
hosts:
-http://server1.com
-http://server2.com
The new yaml will be
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. 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!
CodePudding user response:
Correct way would be to release v2 of your package for new structure of Settings
. Users of v2 can use new structure and existing users can keep using old structure with v1 of your package.
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
- array of
string
for old yaml - array of
map[string]interface{}
for new yaml
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.