Browse Source

cache

master
3136352472 5 years ago
parent
commit
a3e65c22c5
  1. 34
      govue/cache.go
  2. 2
      govue/cmd/main.go
  3. 27
      govue/govue.go

34
govue/cache.go

@ -0,0 +1,34 @@
package govue
import (
"sync"
"time"
)
var cache sync.Map
type mcache struct {
html string
creation int64
timeoutSec int64
}
func GetCache(key string) string {
v, _ := cache.Load(key)
if v != nil {
mc := v.(*mcache)
if time.Now().Unix() < mc.creation+mc.timeoutSec {
//log.Println("加载缓存")
return mc.html
}
}
return ""
}
func SetCache(key string, val string, timeoutSec int64) {
cache.Store(key, &mcache{
html: val,
creation: time.Now().Unix(),
timeoutSec: timeoutSec,
})
}

2
govue/cmd/main.go

@ -74,7 +74,7 @@ func main() {
config.ErrorPage404 = errorPage404
}
gv.SetErrorPage404(config.ErrorPage404)
gv.SetCacheSec(5)
if err != nil {
panic(err)
}

27
govue/govue.go

@ -23,6 +23,7 @@ type GoVue struct {
Resources *assetfs.AssetFS
IsDebugMode bool
jsRuntimePool *pool.JsRuntimePool
CacheSec int64
}
func NewGoVueDefaultConfig(debug bool) (gv *GoVue, err error) {
@ -46,6 +47,10 @@ func NewGoVue(useJsPath string, staticPath string, debug bool) (gv *GoVue, err e
return
}
func (gv *GoVue) SetCacheSec(cacheSec int64) {
gv.CacheSec = cacheSec
}
func (gv *GoVue) SetErrorPage404(page string) {
gv.ErrorPage404 = page
}
@ -146,6 +151,16 @@ func (gv *GoVue) StartPoolLog() {
}
func (gv *GoVue) LoadStaticResources(request *http.Request, goExtDataS ...interface{}) (result []byte, err error) {
cacheKey := fmt.Sprintf("%s|%s", request.URL.Path, request.URL.RawQuery)
if gv.CacheSec > 0 {
html := GetCache(cacheKey)
if html != "" {
//log.Println("加载缓存")
return []byte(html), nil
}
}
//log.Println("非缓存", cacheKey)
var staticDir string
var filePath = request.URL.Path
@ -184,9 +199,16 @@ func (gv *GoVue) LoadStaticResources(request *http.Request, goExtDataS ...interf
result, err = ioutil.ReadFile(filePath)
if err != nil {
return gv.renderErrPage(404, request, goExtDataS...)
result, err = gv.renderErrPage(404, request, goExtDataS...)
if gv.CacheSec > 0 {
SetCache(cacheKey, string(result), gv.CacheSec)
}
return
}
if filepath.Ext(filePath) != ".html" && filepath.Ext(filePath) != ".vue" {
if gv.CacheSec > 0 {
SetCache(cacheKey, string(result), gv.CacheSec)
}
return
}
@ -203,6 +225,9 @@ func (gv *GoVue) LoadStaticResources(request *http.Request, goExtDataS ...interf
err = jr.Render(filePath, fmt.Sprintf("http://%s%s", request.Host, request.RequestURI), string(result), goExtData, func(data string) {
result = []byte(data)
if gv.CacheSec > 0 {
SetCache(cacheKey, string(result), gv.CacheSec)
}
})
if err != nil {
result = []byte(err.Error())

Loading…
Cancel
Save