config.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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{}, opts ...Option) error {
  16. content, err := ioutil.ReadFile(file)
  17. if err != nil {
  18. return err
  19. }
  20. loader, ok := loaders[path.Ext(file)]
  21. if !ok {
  22. return fmt.Errorf("unrecoginized file type: %s", file)
  23. }
  24. var opt options
  25. for _, o := range opts {
  26. o(&opt)
  27. }
  28. if opt.env {
  29. return loader([]byte(os.ExpandEnv(string(content))), v)
  30. } else {
  31. return loader(content, v)
  32. }
  33. }
  34. func LoadConfigFromJsonBytes(content []byte, v interface{}) error {
  35. return mapping.UnmarshalJsonBytes(content, v)
  36. }
  37. func LoadConfigFromYamlBytes(content []byte, v interface{}) error {
  38. return mapping.UnmarshalYamlBytes(content, v)
  39. }
  40. func MustLoad(path string, v interface{}, opts ...Option) {
  41. if err := LoadConfig(path, v, opts...); err != nil {
  42. log.Fatalf("error: config file %s, %s", path, err.Error())
  43. }
  44. }