mirror of https://github.com/jlelse/GoBlog
Small cache things
This commit is contained in:
parent
77f6a53a7e
commit
b9856175b9
20
cache.go
20
cache.go
|
@ -34,10 +34,10 @@ func initCache() {
|
|||
func cacheMiddleware(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if appConfig.Cache.Enable &&
|
||||
// check bypass query
|
||||
!(r.URL.Query().Get("cache") == "0") &&
|
||||
// check method
|
||||
(r.Method == http.MethodGet || r.Method == http.MethodHead) {
|
||||
(r.Method == http.MethodGet || r.Method == http.MethodHead) &&
|
||||
// check bypass query
|
||||
!(r.URL.Query().Get("cache") == "0") {
|
||||
key := cacheKey(r)
|
||||
// Get cache or render it
|
||||
cacheInterface, _, _ := cacheGroup.Do(key, func() (interface{}, error) {
|
||||
|
@ -72,7 +72,7 @@ func cacheMiddleware(next http.Handler) http.Handler {
|
|||
}
|
||||
|
||||
func cacheKey(r *http.Request) string {
|
||||
return slashTrimmedPath(r)
|
||||
return r.URL.String()
|
||||
}
|
||||
|
||||
func setCacheHeaders(w http.ResponseWriter, cacheTimeString string, expiresTimeString string) {
|
||||
|
@ -98,16 +98,16 @@ func getCache(key string, next http.Handler, r *http.Request) *cacheItem {
|
|||
cacheMutex.RUnlock()
|
||||
if !ok || item.expired() {
|
||||
// No cache available
|
||||
item = &cacheItem{}
|
||||
// Record request
|
||||
recorder := httptest.NewRecorder()
|
||||
next.ServeHTTP(recorder, r)
|
||||
// Cache values from recorder
|
||||
now := time.Now()
|
||||
item.creationTime = now.Unix()
|
||||
item.code = recorder.Code
|
||||
item.header = recorder.Header()
|
||||
item.body = recorder.Body.Bytes()
|
||||
item = &cacheItem{
|
||||
creationTime: time.Now().Unix(),
|
||||
code: recorder.Code,
|
||||
header: recorder.Header(),
|
||||
body: recorder.Body.Bytes(),
|
||||
}
|
||||
// Save cache
|
||||
cacheMutex.Lock()
|
||||
cacheMap[key] = item
|
||||
|
|
Loading…
Reference in New Issue