Stuff
This commit is contained in:
@@ -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
|
||||
}
|
||||
|
||||
@@ -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))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
[numbers]
|
||||
ary = [1, 2, 3]
|
||||
i = 123
|
||||
|
||||
[words]
|
||||
foo = "bar"
|
||||
[words.list]
|
||||
foo = ["buzz", "fizz"]
|
||||
Reference in New Issue
Block a user