wangchuanjin 4 years ago
parent
commit
6cef54484b
1 changed files with 98 additions and 0 deletions
  1. 98 0
      common/config.go

+ 98 - 0
common/config.go

@@ -0,0 +1,98 @@
+package common
+
+import (
+	"encoding/json"
+	"errors"
+	"io/ioutil"
+
+	"os"
+	"strings"
+	"sync"
+)
+
+var lock sync.Mutex
+
+//读取配置文件,可以有2个参数,
+//第一个参数是配置文件路径,如果只有一个参数时,默认配置文件路径为./config.json
+//第二个参数是要注入的对象,可以是结构体,或者是interface对象
+func ReadConfig(config ...interface{}) {
+	var r *os.File
+	if len(config) > 1 {
+		filepath, _ := config[0].(string)
+		r, _ = os.Open(filepath)
+		defer r.Close()
+		bs, _ := ioutil.ReadAll(r)
+		json.Unmarshal(bs, config[1])
+	} else {
+		r, _ = os.Open("./config.json")
+		defer r.Close()
+		bs, _ := ioutil.ReadAll(r)
+		json.Unmarshal(bs, config[0])
+	}
+}
+
+//程序修改SysConfig配置表后,调用写入配置文件
+func WriteSysConfig(config ...interface{}) {
+	var r *os.File
+	var configobj interface{}
+	if len(config) > 1 {
+		filepath, _ := config[0].(string)
+		r, _ = os.OpenFile(filepath, os.O_WRONLY|os.O_TRUNC, 0x644)
+		configobj = config[1]
+	} else {
+		r, _ = os.OpenFile("./config.json", os.O_WRONLY|os.O_TRUNC, 0x644)
+		configobj = config[0]
+	}
+	defer r.Close()
+	if s, ok := configobj.(string); ok {
+		r.Write([]byte(s))
+
+	} else {
+		bs, _ := json.Marshal(configobj)
+		r.Write(bs)
+	}
+}
+
+//按路径查map配置
+//TODO 暂未处理查询路径中是数组的情况
+func GetPropertie(qpath /*map的查询路径*/ string, config map[string]interface{}) (ret interface{}) {
+	//tmp := new(map[string]interface{})
+	tmp := config
+	qps := strings.Split(qpath, ".")
+	length := len(qps)
+	for i, v := range qps {
+		if v1, ok := tmp[v]; ok {
+			//log.Println("类型:", reflect.TypeOf(v1))
+			if v2, ok2 := v1.(map[string]interface{}); ok2 {
+				tmp = v2
+			} else if i == length-1 {
+				//map断了,没有下一层了
+				ret = v1
+			}
+		} else {
+			return nil
+		}
+	}
+	return
+}
+
+//设置值
+//TODO 未处理数组,仅处理map递归型
+func SetPropertie(qpath string, value interface{}, config map[string]interface{}) (err error) {
+	tmp := config
+	qps := strings.Split(qpath, ".")
+	length := len(qps)
+	for i := 0; i < length-1; i++ {
+		if v1, ok1 := (tmp[qps[i]]).(map[string]interface{}); ok1 {
+			tmp = v1
+		} else {
+			err = errors.New("路径查找失败")
+			break
+		}
+
+	}
+	if err == nil {
+		tmp[qps[length-1]] = value
+	}
+	return
+}