This commit is contained in:
2018-06-24 16:36:44 +02:00
parent 8ad4e70623
commit a4b74992c4
6 changed files with 127 additions and 12 deletions
+33
View File
@@ -1 +1,34 @@
package config
import (
"github.com/BurntSushi/toml"
)
var configs = map[string]interface{}{}
// Require registers a request for package configuration.
func Require(key string, dest interface{}) {
configs[key] = dest
}
// Load reads the config file and distributes provided configuration to
// requested destinations.
func Load(path string) error {
var conf map[string]toml.Primitive
meta, err := toml.DecodeFile(path, &conf)
if err != nil {
return err
}
for key, prim := range conf {
dest, ok := configs[key]
if !ok {
continue
}
err := meta.PrimitiveDecode(prim, dest)
if err != nil {
return err
}
}
return nil
}
+48
View File
@@ -0,0 +1,48 @@
package config
import (
"testing"
"github.com/google/go-cmp/cmp"
)
func TestConfig(t *testing.T) {
type numbers struct {
Ary []int `toml:"ary"`
I int `toml:"i"`
}
var nums numbers
Require("numbers", &nums)
numsExp := numbers{
Ary: []int{1, 2, 3},
I: 123,
}
type words struct {
Foo string `toml:"foo"`
List struct {
Foo []string `toml:"foo"`
} `toml:"list"`
}
var w words
Require("words", &w)
wordsExp := words{
Foo: "bar",
List: struct {
Foo []string `toml:"foo"`
}{
Foo: []string{"buzz", "fizz"},
},
}
err := Load("example.toml")
if err != nil {
t.Fatalf("Failed to load config: %v", err)
}
if !cmp.Equal(numsExp, nums) {
t.Errorf("Numbers mismatch: %s", cmp.Diff(numsExp, nums))
}
if !cmp.Equal(wordsExp, w) {
t.Errorf("Words mismatch: %s", cmp.Diff(wordsExp, w))
}
}
+8
View File
@@ -0,0 +1,8 @@
[numbers]
ary = [1, 2, 3]
i = 123
[words]
foo = "bar"
[words.list]
foo = ["buzz", "fizz"]