123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112 |
- package common
- import (
- "encoding/json"
- "errors"
- "github.com/gogf/gf/v2/os/gfile"
- "io/ioutil"
- "log"
- "path/filepath"
- "os"
- "strings"
- "sync"
- )
- var lock sync.Mutex
- // 读取配置文件,可以有2个参数,
- // 第一个参数是配置文件路径,如果只有一个参数时,默认配置文件路径为./config.json
- // 第二个参数是要注入的对象,可以是结构体,或者是interface对象
- func ReadConfig(config ...interface{}) {
- filePath := "./config.json"
- var object any
- if len(config) > 1 {
- filePath, _ = config[0].(string)
- object = config[1]
- } else {
- object = config[0]
- }
- r, e := os.Open(filePath)
- if e != nil {
- newFilePath, _ := gfile.Search(filepath.Base(filePath))
- if newFilePath != "" {
- r, e = os.Open(newFilePath)
- }
- }
- if e != nil {
- log.Println(filePath, "打开文件出错", e)
- return
- }
- defer r.Close()
- bs, _ := ioutil.ReadAll(r)
- if e = json.Unmarshal(bs, object); e != nil {
- log.Println(filePath, " json格式异常")
- }
- }
- // 程序修改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
- }
|