config.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. package conf
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "log"
  6. "os"
  7. "path"
  8. "git.i2edu.net/i2/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. // LoadConfig loads config into v from file, .json, .yaml and .yml are acceptable.
  16. func LoadConfig(file string, v interface{}, opts ...Option) error {
  17. content, err := ioutil.ReadFile(file)
  18. if err != nil {
  19. return err
  20. }
  21. loader, ok := loaders[path.Ext(file)]
  22. if !ok {
  23. return fmt.Errorf("unrecognized file type: %s", file)
  24. }
  25. var opt options
  26. for _, o := range opts {
  27. o(&opt)
  28. }
  29. if opt.env {
  30. return loader([]byte(os.ExpandEnv(string(content))), v)
  31. }
  32. return loader(content, v)
  33. }
  34. // LoadConfigFromJsonBytes loads config into v from content json bytes.
  35. func LoadConfigFromJsonBytes(content []byte, v interface{}) error {
  36. return mapping.UnmarshalJsonBytes(content, v)
  37. }
  38. // LoadConfigFromYamlBytes loads config into v from content yaml bytes.
  39. func LoadConfigFromYamlBytes(content []byte, v interface{}) error {
  40. return mapping.UnmarshalYamlBytes(content, v)
  41. }
  42. // MustLoad loads config into v from path, exits on error.
  43. func MustLoad(path string, v interface{}, opts ...Option) {
  44. if err := LoadConfig(path, v, opts...); err != nil {
  45. log.Fatalf("error: config file %s, %s", path, err.Error())
  46. }
  47. }