config.go 940 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. package conf
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "log"
  6. "path"
  7. "github.com/tal-tech/go-zero/core/mapping"
  8. )
  9. var loaders = map[string]func([]byte, interface{}) error{
  10. ".json": LoadConfigFromJsonBytes,
  11. ".yaml": LoadConfigFromYamlBytes,
  12. ".yml": LoadConfigFromYamlBytes,
  13. }
  14. func LoadConfig(file string, v interface{}) error {
  15. if content, err := ioutil.ReadFile(file); err != nil {
  16. return err
  17. } else if loader, ok := loaders[path.Ext(file)]; ok {
  18. return loader(content, v)
  19. } else {
  20. return fmt.Errorf("unrecoginized file type: %s", file)
  21. }
  22. }
  23. func LoadConfigFromJsonBytes(content []byte, v interface{}) error {
  24. return mapping.UnmarshalJsonBytes(content, v)
  25. }
  26. func LoadConfigFromYamlBytes(content []byte, v interface{}) error {
  27. return mapping.UnmarshalYamlBytes(content, v)
  28. }
  29. func MustLoad(path string, v interface{}) {
  30. if err := LoadConfig(path, v); err != nil {
  31. log.Fatalf("error: config file %s, %s", path, err.Error())
  32. }
  33. }