config.go 2.2 KB

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