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 {
|
func cacheMiddleware(next http.Handler) http.Handler {
|
||||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
if appConfig.Cache.Enable &&
|
if appConfig.Cache.Enable &&
|
||||||
// check bypass query
|
|
||||||
!(r.URL.Query().Get("cache") == "0") &&
|
|
||||||
// check method
|
// 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)
|
key := cacheKey(r)
|
||||||
// Get cache or render it
|
// Get cache or render it
|
||||||
cacheInterface, _, _ := cacheGroup.Do(key, func() (interface{}, error) {
|
cacheInterface, _, _ := cacheGroup.Do(key, func() (interface{}, error) {
|
||||||
|
@ -72,7 +72,7 @@ func cacheMiddleware(next http.Handler) http.Handler {
|
||||||
}
|
}
|
||||||
|
|
||||||
func cacheKey(r *http.Request) string {
|
func cacheKey(r *http.Request) string {
|
||||||
return slashTrimmedPath(r)
|
return r.URL.String()
|
||||||
}
|
}
|
||||||
|
|
||||||
func setCacheHeaders(w http.ResponseWriter, cacheTimeString string, expiresTimeString 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()
|
cacheMutex.RUnlock()
|
||||||
if !ok || item.expired() {
|
if !ok || item.expired() {
|
||||||
// No cache available
|
// No cache available
|
||||||
item = &cacheItem{}
|
|
||||||
// Record request
|
// Record request
|
||||||
recorder := httptest.NewRecorder()
|
recorder := httptest.NewRecorder()
|
||||||
next.ServeHTTP(recorder, r)
|
next.ServeHTTP(recorder, r)
|
||||||
// Cache values from recorder
|
// Cache values from recorder
|
||||||
now := time.Now()
|
item = &cacheItem{
|
||||||
item.creationTime = now.Unix()
|
creationTime: time.Now().Unix(),
|
||||||
item.code = recorder.Code
|
code: recorder.Code,
|
||||||
item.header = recorder.Header()
|
header: recorder.Header(),
|
||||||
item.body = recorder.Body.Bytes()
|
body: recorder.Body.Bytes(),
|
||||||
|
}
|
||||||
// Save cache
|
// Save cache
|
||||||
cacheMutex.Lock()
|
cacheMutex.Lock()
|
||||||
cacheMap[key] = item
|
cacheMap[key] = item
|
||||||
|
|
Loading…
Reference in New Issue