Recently we moved some of our hard-coded web-app configuration values into a YAML file. Arguing aside (YAML vs TOML vs …), YAML does a great job being easily readable by us - humans. By default, the yaml library marshals maps into map[string]interface{}
, requiring a small change to get it marshaled into map[string]string
.
Working with a [string]string map is easier and faster compared to [string]interface{} maps. By default, the go-yaml library converts ‘map fields’ into map[string]interface{}
.
We have a list of allowed GCS buckets for clients, and we moved them to our configuration file. Since I wanted to avoid casting interfaces to strings, I changed go-yaml’s default behavior, and marshalled values to map[string]string
. To achieve this:
buckets:
profile_pictures: profile-pictures-dev
featured-images: featured-images-dev
timeline-images: timeline-images-dev
// Buckets represents buckets configuration
type Buckets struct {
Names map[string]string `yaml:"buckets,omitempty"`
}
// UnmarshalYAML is used to unmarshal into map[string]string
func (b *Buckets) UnmarshalYAML(unmarshal func(interface{}) error) error {
return unmarshal(&b.Names)
}
This little change marshals maps into map[string]string
.