I have a YAML like one below.
connections:
- name: demo
hosts:
- demo.example.com:9200
username: admin
password: password
ssl: true
ssl_verify: true
version: 7
- name: test
hosts:
- "test.example.com:9200"
username: admin
password: password
As you can see ssl
and ssl_verify
is not set in the second item of the list. I want them by default to be true
, however, it is not happening. I tried different solutions.
- Viper defaults - does not work.
viper.SetDefault("connections[].ssl", "true")
- https://github.com/creasty/defaults - does not work.
type Config struct {
Connections []struct {
Name string
Hosts []string
Username string
Password string
Ssl bool `default:"true"`
SslVerify bool `default:"true"`
Version int
}
}
...
err := defaults.Set(config)
Manually looping through the list of structures. While these method work with strings, it does not work with boolean values because they are already initialized with
false
after unmarshalling and we don't know for sure whetherfalse
is entered by the user or not.Using pointers with boolean values. This works as uninitialized values are equal to
nil
and they are easy to catch. However, it will require to dereference pointers when using config struct, which is not very convenient. Alternatively, a new struct can be generated based on the one that comes from unmarshalling.
type Config struct {
Connections []struct {
Name string
Hosts []string
Username string
Password string
Ssl *bool
SslVerify *bool
Version int
}
}
- Using hashmap instead of struct. This works because empty values are not initialized, however, it will require to run checks on the map elements before accessing them or to convert a map to the struct.
Solutions 4 and 5 will likely work, but I am wondering if there anything better than that.
Any ideas?