knadh / koanf

Simple, extremely lightweight, extensible, configuration management library for Go. Support for JSON, TOML, YAML, env, command line, file, S3 etc. Alternative to viper.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

unmarshall dict key to struct property

bambamboole opened this issue Β· comments

Hey guys,
I am new to Go and don't know exactly if this is a yaml or koanf question, so sorry in advance if this is not the right place πŸ™ˆ .

I am trying to unmarshall yaml dict keys onto a property of a struct rather than the key of a map.
Given this yaml

commands:
    php:
        service: php
        bin: /bin/php
    node:
        service: node
        bin: /bin/node

I am able to unmarshall this into a struct like this:

type Config struct {
	Commands map[string]struct {
		Service string
		Bin     string
	}
}

But how am I able to unmarshall it into a struct like this:

type Config struct {
	Commands []struct {
		Name    string    // <-- this should be key from the yaml (i.e. php or node)
		Service string
		Bin     string
	}
}
type Config struct {
	Commands []struct {
		Name    string `koanf:"name"`
		Service string `koanf:"service"`
		Bin     string `koanf:"bin"`
	} `koanf:"commands"`
}

(Make sure the koanf tags match the YAML field names).

---
commands:
- name: xxx
  service: xxx
  bin: xxx
- name: yyy
  service: yyy
  bin: yyy

This should work.