1
0
Fork 0
gobelt/config/config.go

48 lines
980 B
Go
Raw Normal View History

2018-06-24 01:06:28 +00:00
package config
2018-06-24 14:36:44 +00:00
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
}
2018-06-24 22:22:27 +00:00
// Load ...
func Load(src string) error {
return load(src, toml.Decode)
}
// LoadFile reads the config file and distributes provided configuration to
2018-06-24 14:36:44 +00:00
// requested destinations.
2018-06-24 22:22:27 +00:00
func LoadFile(path string) error {
return load(path, toml.DecodeFile)
}
func load(from string, withFn func(string, interface{}) (toml.MetaData, error)) error {
var sections map[string]toml.Primitive
meta, err := withFn(from, &sections)
2018-06-24 14:36:44 +00:00
if err != nil {
return err
}
2018-06-24 22:22:27 +00:00
return decode(meta, sections)
}
2018-06-24 14:36:44 +00:00
2018-06-24 22:22:27 +00:00
func decode(meta toml.MetaData, sections map[string]toml.Primitive) error {
for section, conf := range sections {
dest, ok := configs[section]
2018-06-24 14:36:44 +00:00
if !ok {
continue
}
2018-06-24 22:22:27 +00:00
err := meta.PrimitiveDecode(conf, dest)
2018-06-24 14:36:44 +00:00
if err != nil {
return err
}
}
return nil
}