config.go 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. package common
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "github.com/gogf/gf/v2/os/gfile"
  6. "io/ioutil"
  7. "log"
  8. "path/filepath"
  9. "os"
  10. "strings"
  11. "sync"
  12. )
  13. var lock sync.Mutex
  14. // 读取配置文件,可以有2个参数,
  15. // 第一个参数是配置文件路径,如果只有一个参数时,默认配置文件路径为./config.json
  16. // 第二个参数是要注入的对象,可以是结构体,或者是interface对象
  17. func ReadConfig(config ...interface{}) {
  18. filePath := "./config.json"
  19. var object any
  20. if len(config) > 1 {
  21. filePath, _ = config[0].(string)
  22. object = config[1]
  23. } else {
  24. object = config[0]
  25. }
  26. r, e := os.Open(filePath)
  27. if e != nil {
  28. newFilePath, _ := gfile.Search(filepath.Base(filePath))
  29. if newFilePath != "" {
  30. r, e = os.Open(newFilePath)
  31. }
  32. }
  33. if e != nil {
  34. log.Println(filePath, "打开文件出错", e)
  35. return
  36. }
  37. defer r.Close()
  38. bs, _ := ioutil.ReadAll(r)
  39. if e = json.Unmarshal(bs, object); e != nil {
  40. log.Println(filePath, " json格式异常")
  41. }
  42. }
  43. // 程序修改SysConfig配置表后,调用写入配置文件
  44. func WriteSysConfig(config ...interface{}) {
  45. var r *os.File
  46. var configobj interface{}
  47. if len(config) > 1 {
  48. filepath, _ := config[0].(string)
  49. r, _ = os.OpenFile(filepath, os.O_WRONLY|os.O_TRUNC, 0x644)
  50. configobj = config[1]
  51. } else {
  52. r, _ = os.OpenFile("./config.json", os.O_WRONLY|os.O_TRUNC, 0x644)
  53. configobj = config[0]
  54. }
  55. defer r.Close()
  56. if s, ok := configobj.(string); ok {
  57. r.Write([]byte(s))
  58. } else {
  59. bs, _ := json.Marshal(configobj)
  60. r.Write(bs)
  61. }
  62. }
  63. // 按路径查map配置
  64. // TODO 暂未处理查询路径中是数组的情况
  65. func GetPropertie(qpath /*map的查询路径*/ string, config map[string]interface{}) (ret interface{}) {
  66. //tmp := new(map[string]interface{})
  67. tmp := config
  68. qps := strings.Split(qpath, ".")
  69. length := len(qps)
  70. for i, v := range qps {
  71. if v1, ok := tmp[v]; ok {
  72. //log.Println("类型:", reflect.TypeOf(v1))
  73. if v2, ok2 := v1.(map[string]interface{}); ok2 {
  74. tmp = v2
  75. } else if i == length-1 {
  76. //map断了,没有下一层了
  77. ret = v1
  78. }
  79. } else {
  80. return nil
  81. }
  82. }
  83. return
  84. }
  85. // 设置值
  86. // TODO 未处理数组,仅处理map递归型
  87. func SetPropertie(qpath string, value interface{}, config map[string]interface{}) (err error) {
  88. tmp := config
  89. qps := strings.Split(qpath, ".")
  90. length := len(qps)
  91. for i := 0; i < length-1; i++ {
  92. if v1, ok1 := (tmp[qps[i]]).(map[string]interface{}); ok1 {
  93. tmp = v1
  94. } else {
  95. err = errors.New("路径查找失败")
  96. break
  97. }
  98. }
  99. if err == nil {
  100. tmp[qps[length-1]] = value
  101. }
  102. return
  103. }