mirror of
https://github.com/caddyserver/caddy.git
synced 2025-02-05 16:48:27 +03:00
adding mutexes to protect the entries map
This commit is contained in:
parent
8a7063bfa2
commit
20f2d060ea
1 changed files with 8 additions and 0 deletions
8
middleware/cache/cache.go
vendored
8
middleware/cache/cache.go
vendored
|
@ -6,6 +6,7 @@ import (
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/http/httptest"
|
"net/http/httptest"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/dustin/go-humanize"
|
"github.com/dustin/go-humanize"
|
||||||
|
@ -13,6 +14,7 @@ import (
|
||||||
)
|
)
|
||||||
|
|
||||||
// Example line in CaddyFile: cache 60 128mb 10mb
|
// Example line in CaddyFile: cache 60 128mb 10mb
|
||||||
|
// Arguments are max-age in seconds, max cache size, max size for an individual file in the cache
|
||||||
|
|
||||||
// Cache is an http.Handler that can remembers and sends back stored responses
|
// Cache is an http.Handler that can remembers and sends back stored responses
|
||||||
type Cache struct {
|
type Cache struct {
|
||||||
|
@ -20,6 +22,7 @@ type Cache struct {
|
||||||
Lifetime int
|
Lifetime int
|
||||||
Entries map[string]CacheEntry // url -> entry
|
Entries map[string]CacheEntry // url -> entry
|
||||||
Rule Rule
|
Rule Rule
|
||||||
|
Mutex sync.RWMutex
|
||||||
}
|
}
|
||||||
|
|
||||||
type CacheEntry struct {
|
type CacheEntry struct {
|
||||||
|
@ -105,7 +108,10 @@ func (c Cache) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) {
|
||||||
if r.Method == "GET" {
|
if r.Method == "GET" {
|
||||||
key := r.RequestURI
|
key := r.RequestURI
|
||||||
now := time.Now().Unix()
|
now := time.Now().Unix()
|
||||||
|
|
||||||
|
c.Mutex.RLock()
|
||||||
entry, inCache := c.Entries[key]
|
entry, inCache := c.Entries[key]
|
||||||
|
c.Mutex.RUnlock()
|
||||||
|
|
||||||
if inCache && now-entry.created < c.Rule.MaxAge && ClientAllowsCaching(r) {
|
if inCache && now-entry.created < c.Rule.MaxAge && ClientAllowsCaching(r) {
|
||||||
entry.lastUsed = time.Now().Unix()
|
entry.lastUsed = time.Now().Unix()
|
||||||
|
@ -120,7 +126,9 @@ func (c Cache) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) {
|
||||||
|
|
||||||
if normalResponse && bodySize < c.Rule.MaxCacheEntrySize && ServerAllowsCaching(record.Header()) {
|
if normalResponse && bodySize < c.Rule.MaxCacheEntrySize && ServerAllowsCaching(record.Header()) {
|
||||||
// adds response to cache
|
// adds response to cache
|
||||||
|
c.Mutex.Lock()
|
||||||
c.Entries[key] = entry
|
c.Entries[key] = entry
|
||||||
|
c.Mutex.Unlock()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
Loading…
Reference in a new issue