You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

config.go 1.0 kB

1234567891011121314151617181920212223242526272829303132333435363738
  1. package config
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "os"
  6. "path/filepath"
  7. "github.com/imdario/mergo"
  8. )
  9. // Load 加载配置文件
  10. func Load(filePath string, cfg interface{}) error {
  11. fileData, err := os.ReadFile(filePath)
  12. if err != nil {
  13. return err
  14. }
  15. return json.Unmarshal(fileData, cfg)
  16. }
  17. // DefaultLoad 默认的加载配置的方式:
  18. // 从应用程序上上级的conf目录中读取,文件名:<moduleName>.config.json
  19. func DefaultLoad(modeulName string, defCfg interface{}) error {
  20. execPath, err := os.Executable()
  21. if err != nil {
  22. return err
  23. }
  24. // TODO 可以考虑根据环境变量读取不同的配置
  25. configFilePath := filepath.Join(filepath.Dir(execPath), "..", "confs", fmt.Sprintf("%s.config.json", modeulName))
  26. return Load(configFilePath, defCfg)
  27. }
  28. // Merge 合并两个配置结构体。会将src中的非空字段覆盖到dst的同名字段中。两个结构的类型必须相同
  29. func Merge(dst interface{}, src interface{}) error {
  30. return mergo.Merge(dst, src)
  31. }