配置管理新增修改配置目录路径接口,完善路由控制示例

This commit is contained in:
John
2018-01-04 11:08:23 +08:00
parent ce3b573c67
commit 3e2a3cf2f2
3 changed files with 43 additions and 8 deletions

View File

@ -11,6 +11,7 @@ import (
"gitee.com/johng/gf/g/os/gfile"
"gitee.com/johng/gf/g/container/gmap"
"gitee.com/johng/gf/g/encoding/gjson"
"sync"
)
const (
@ -19,36 +20,46 @@ const (
// 配置管理对象
type Config struct {
mu sync.RWMutex // 并发互斥锁
path string // 配置文件存放目录,绝对路径
jsons *gmap.StringInterfaceMap // 配置文件对象
}
// 生成一个配置管理对象
func New(path string) *Config {
return &Config{
return &Config {
path : path,
jsons : gmap.NewStringInterfaceMap(),
}
}
// 判断从哪个配置文件中获取内容
func (c *Config) file(files []string) string {
func (c *Config) filePath(files []string) string {
file := gDEFAULT_CONFIG_FILE
if len(files) > 0 {
file = files[0]
}
return file + ".json"
c.mu.RLock()
fpath := c.path + gfile.Separator + file
c.mu.RUnlock()
return fpath + ".json"
}
// 设置配置管理器的配置文件存放目录绝对路径
func (c *Config) SetPath(path string) {
c.mu.Lock()
c.path = path
c.mu.Unlock()
}
// 添加配置文件到配置管理器中,第二个参数为非必须,如果不输入表示添加进入默认的配置名称中
func (c *Config) getJson(files []string) *gjson.Json {
file := c.file(files)
if r := c.jsons.Get(file); r != nil {
fpath := c.filePath(files)
if r := c.jsons.Get(fpath); r != nil {
return r.(*gjson.Json)
}
path := c.path + gfile.Separator + file
if j, err := gjson.Load(path); err == nil {
c.jsons.Set(file, j)
if j, err := gjson.Load(fpath); err == nil {
c.jsons.Set(fpath, j)
return j
}
return nil

View File

@ -0,0 +1,12 @@
package demo
import "gitee.com/johng/gf/g/net/ghttp"
func init() {
ghttp.GetServer().BindHandler("/list", List)
ghttp.GetServer().Router.SetRule(`\/list\/page\/(\d+)[\/\?]*`, "/list?page=$1&")
}
func List(r *ghttp.Request) {
r.Response.WriteString("list page:" + r.GetQueryString("page"))
}

View File

@ -0,0 +1,12 @@
package demo
import "gitee.com/johng/gf/g/net/ghttp"
func init() {
ghttp.GetServer().BindHandler("/router-patch", RouterPatch)
ghttp.GetServer().Router.SetPatchRule(`\/list\?page=(\d+)&*`, "/list/page/$1?")
}
func RouterPatch(r *ghttp.Request) {
r.Response.WriteString(`<a href="/list?page=2&ajax=1">page2</a>`)
}