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

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