read_config.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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. r, _ = os.Open(filepath)
  19. defer r.Close()
  20. bs, _ := ioutil.ReadAll(r)
  21. json.Unmarshal(bs, config[1])
  22. } else {
  23. r, _ = os.Open("./config.json")
  24. defer r.Close()
  25. bs, _ := ioutil.ReadAll(r)
  26. json.Unmarshal(bs, config[0])
  27. }
  28. }
  29. //程序修改SysConfig配置表后,调用写入配置文件
  30. func WriteSysConfig(config ...interface{}) {
  31. var r *os.File
  32. var configobj interface{}
  33. if len(config) > 1 {
  34. filepath, _ := config[0].(string)
  35. r, _ = os.OpenFile(filepath, os.O_WRONLY|os.O_TRUNC, 0x644)
  36. configobj = config[1]
  37. } else {
  38. r, _ = os.OpenFile("./config.json", os.O_WRONLY|os.O_TRUNC, 0x644)
  39. configobj = config[0]
  40. }
  41. defer r.Close()
  42. if s, ok := configobj.(string); ok {
  43. r.Write([]byte(s))
  44. } else {
  45. bs, _ := json.Marshal(configobj)
  46. r.Write(bs)
  47. }
  48. }
  49. //按路径查map配置
  50. //TODO 暂未处理查询路径中是数组的情况
  51. func GetPropertie(qpath /*map的查询路径*/ string, config map[string]interface{}) (ret interface{}) {
  52. //tmp := new(map[string]interface{})
  53. tmp := config
  54. qps := strings.Split(qpath, ".")
  55. length := len(qps)
  56. for i, v := range qps {
  57. if v1, ok := tmp[v]; ok {
  58. //log.Println("类型:", reflect.TypeOf(v1))
  59. if v2, ok2 := v1.(map[string]interface{}); ok2 {
  60. tmp = v2
  61. } else if i == length-1 {
  62. //map断了,没有下一层了
  63. ret = v1
  64. }
  65. } else {
  66. return nil
  67. }
  68. }
  69. return
  70. }
  71. //设置值
  72. //TODO 未处理数组,仅处理map递归型
  73. func SetPropertie(qpath string, value interface{}, config map[string]interface{}) (err error) {
  74. tmp := config
  75. qps := strings.Split(qpath, ".")
  76. length := len(qps)
  77. for i := 0; i < length-1; i++ {
  78. if v1, ok1 := (tmp[qps[i]]).(map[string]interface{}); ok1 {
  79. tmp = v1
  80. } else {
  81. err = errors.New("路径查找失败")
  82. break
  83. }
  84. }
  85. if err == nil {
  86. tmp[qps[length-1]] = value
  87. }
  88. return
  89. }