1
0

config.go 976 B

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