config.go 2.3 KB

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