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.3 kB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. package config
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "github.com/imdario/mergo"
  6. "os"
  7. "path/filepath"
  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. // json.Unmarshal用于将JSON解码成结构体
  16. return json.Unmarshal(fileData, cfg)
  17. }
  18. // DefaultLoad 默认的加载配置的方式:
  19. // 从应用程序上上级的conf目录中读取,文件名:<moduleName>.config.json
  20. func DefaultLoad(modeulName string, defCfg interface{}) error {
  21. // 获取当前进程文件执行路径,并判断是否为空
  22. execPath, err := os.Executable()
  23. if err != nil {
  24. return err
  25. }
  26. // TODO 可以考虑根据环境变量读取不同的配置
  27. // filepath.Join用于将多个路径组合成一个路径
  28. configFilePath := filepath.Join(filepath.Dir(execPath), "..", "confs", fmt.Sprintf("%s.config.json", modeulName))
  29. configFilePath = "D:\\Work\\Codes\\workspace\\workspace\\scheduler\\common\\assets\\confs\\middleware.json"
  30. return Load(configFilePath, defCfg)
  31. }
  32. // Merge 合并两个配置结构体。会将src中的非空字段覆盖到dst的同名字段中。两个结构的类型必须相同
  33. func Merge(dst interface{}, src interface{}) error {
  34. return mergo.Merge(dst, src)
  35. }