config.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package conf
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "log"
  6. "os"
  7. "path"
  8. "strings"
  9. "github.com/zeromicro/go-zero/core/mapping"
  10. )
  11. var loaders = map[string]func([]byte, interface{}) error{
  12. ".json": LoadFromJsonBytes,
  13. ".toml": LoadFromTomlBytes,
  14. ".yaml": LoadFromYamlBytes,
  15. ".yml": LoadFromYamlBytes,
  16. }
  17. // Load loads config into v from file, .json, .yaml and .yml are acceptable.
  18. func Load(file string, v interface{}, opts ...Option) error {
  19. content, err := ioutil.ReadFile(file)
  20. if err != nil {
  21. return err
  22. }
  23. loader, ok := loaders[strings.ToLower(path.Ext(file))]
  24. if !ok {
  25. return fmt.Errorf("unrecognized file type: %s", file)
  26. }
  27. var opt options
  28. for _, o := range opts {
  29. o(&opt)
  30. }
  31. if opt.env {
  32. return loader([]byte(os.ExpandEnv(string(content))), v)
  33. }
  34. return loader(content, v)
  35. }
  36. // LoadConfig loads config into v from file, .json, .yaml and .yml are acceptable.
  37. // Deprecated: use Load instead.
  38. func LoadConfig(file string, v interface{}, opts ...Option) error {
  39. return Load(file, v, opts...)
  40. }
  41. // LoadFromJsonBytes loads config into v from content json bytes.
  42. func LoadFromJsonBytes(content []byte, v interface{}) error {
  43. return mapping.UnmarshalJsonBytes(content, v)
  44. }
  45. // LoadConfigFromJsonBytes loads config into v from content json bytes.
  46. // Deprecated: use LoadFromJsonBytes instead.
  47. func LoadConfigFromJsonBytes(content []byte, v interface{}) error {
  48. return LoadFromJsonBytes(content, v)
  49. }
  50. // LoadFromTomlBytes loads config into v from content toml bytes.
  51. func LoadFromTomlBytes(content []byte, v interface{}) error {
  52. return mapping.UnmarshalTomlBytes(content, v)
  53. }
  54. // LoadFromYamlBytes loads config into v from content yaml bytes.
  55. func LoadFromYamlBytes(content []byte, v interface{}) error {
  56. return mapping.UnmarshalYamlBytes(content, v)
  57. }
  58. // LoadConfigFromYamlBytes loads config into v from content yaml bytes.
  59. // Deprecated: use LoadFromYamlBytes instead.
  60. func LoadConfigFromYamlBytes(content []byte, v interface{}) error {
  61. return LoadFromYamlBytes(content, v)
  62. }
  63. // MustLoad loads config into v from path, exits on error.
  64. func MustLoad(path string, v interface{}, opts ...Option) {
  65. if err := Load(path, v, opts...); err != nil {
  66. log.Fatalf("error: config file %s, %s", path, err.Error())
  67. }
  68. }