August 30, 2018

Marshal YAML fields into map[string]string

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:

  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.

2024 © Emir Ribic - Some rights reserved; please attribute properly and link back. Code snippets are MIT Licensed

Powered by Hugo & Kiss.