Skip to content

Add ConsiderUrlQuery flag #25

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,3 +58,13 @@ The number of seconds to wait between cache cleanup runs.

This determines if the cache status header `Cache-Status` will be added to the
response headers. This header can have the value `hit`, `miss` or `error`.

#### ConsiderUrlQuery (`considerUrlQuery`)

*Default: false*

This determines if a request URL's query parameters are used in the cache key. If
this is set to `false`, the cached response for one request will be returned for
subequent requests that differ only by their URL query parameters. If this is set
to `true`, requests with different query parameters will have different cached
responses stored.
26 changes: 16 additions & 10 deletions cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,18 +14,20 @@ import (

// Config configures the middleware.
type Config struct {
Path string `json:"path" yaml:"path" toml:"path"`
MaxExpiry int `json:"maxExpiry" yaml:"maxExpiry" toml:"maxExpiry"`
Cleanup int `json:"cleanup" yaml:"cleanup" toml:"cleanup"`
AddStatusHeader bool `json:"addStatusHeader" yaml:"addStatusHeader" toml:"addStatusHeader"`
Path string `json:"path" yaml:"path" toml:"path"`
MaxExpiry int `json:"maxExpiry" yaml:"maxExpiry" toml:"maxExpiry"`
Cleanup int `json:"cleanup" yaml:"cleanup" toml:"cleanup"`
AddStatusHeader bool `json:"addStatusHeader" yaml:"addStatusHeader" toml:"addStatusHeader"`
ConsiderUrlQuery bool `json:"considerUrlQuery" yaml:"considerUrlQuery" toml:"considerUrlQuery"`
}

// CreateConfig returns a config instance.
func CreateConfig() *Config {
return &Config{
MaxExpiry: int((5 * time.Minute).Seconds()),
Cleanup: int((5 * time.Minute).Seconds()),
AddStatusHeader: true,
MaxExpiry: int((5 * time.Minute).Seconds()),
Cleanup: int((5 * time.Minute).Seconds()),
AddStatusHeader: true,
ConsiderUrlQuery: false,
}
}

Expand Down Expand Up @@ -78,7 +80,7 @@ type cacheData struct {
func (m *cache) ServeHTTP(w http.ResponseWriter, r *http.Request) {
cs := cacheMissStatus

key := cacheKey(r)
key := cacheKey(m.cfg, r)

b, err := m.cache.Get(key)
if err == nil {
Expand Down Expand Up @@ -146,8 +148,12 @@ func (m *cache) cacheable(r *http.Request, w http.ResponseWriter, status int) (t
return expiry, true
}

func cacheKey(r *http.Request) string {
return r.Method + r.Host + r.URL.Path
func cacheKey(cfg *Config, r *http.Request) string {
key := r.Method + r.Host + r.URL.Path
if !cfg.ConsiderUrlQuery {
return key
}
return key + "?" + r.URL.Query().Encode()
}

type responseWriter struct {
Expand Down
55 changes: 52 additions & 3 deletions cache_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ func TestCache_ServeHTTP(t *testing.T) {
rw.WriteHeader(http.StatusOK)
}

cfg := &Config{Path: dir, MaxExpiry: 10, Cleanup: 20, AddStatusHeader: true}
cfg := &Config{Path: dir, MaxExpiry: 10, Cleanup: 20, AddStatusHeader: true, ConsiderUrlQuery: false}

c, err := New(context.Background(), http.HandlerFunc(next), cfg, "simplecache")
if err != nil {
Expand All @@ -69,15 +69,64 @@ func TestCache_ServeHTTP(t *testing.T) {
c.ServeHTTP(rw, req)

if state := rw.Header().Get("Cache-Status"); state != "miss" {
t.Errorf("unexprect cache state: want \"miss\", got: %q", state)
t.Errorf("unexpected cache state: want \"miss\", got: %q", state)
}

rw = httptest.NewRecorder()

c.ServeHTTP(rw, req)

if state := rw.Header().Get("Cache-Status"); state != "hit" {
t.Errorf("unexprect cache state: want \"hit\", got: %q", state)
t.Errorf("unexpected cache state: want \"hit\", got: %q", state)
}

rw = httptest.NewRecorder()
// Check that the same request with a different URL query hits the same cache entry
c.ServeHTTP(rw, httptest.NewRequest(http.MethodGet, "http://localhost/some/path?queryParam=1", nil))

if state := rw.Header().Get("Cache-Status"); state != "hit" {
t.Errorf("unexpected cache state: want \"hit\", got: %q", state)
}

}

func TestCache_ServeHTTP_ConsiderUrlQuery(t *testing.T) {
dir := createTempDir(t)

next := func(rw http.ResponseWriter, req *http.Request) {
rw.Header().Set("Cache-Control", "max-age=20")
rw.WriteHeader(http.StatusOK)
}

cfg := &Config{Path: dir, MaxExpiry: 10, Cleanup: 20, AddStatusHeader: true, ConsiderUrlQuery: true}

c, err := New(context.Background(), http.HandlerFunc(next), cfg, "simplecache")
if err != nil {
t.Fatal(err)
}

testUrl := "http://localhost/some/path"
req := httptest.NewRequest(http.MethodGet, testUrl, nil)
rw := httptest.NewRecorder()

c.ServeHTTP(rw, req) // Add response to the cache
rw = httptest.NewRecorder()
c.ServeHTTP(rw, req)

if state := rw.Header().Get("Cache-Status"); state != "hit" {
t.Errorf("unexpected cache state: want \"hit\", got: %q", state)
}

rw = httptest.NewRecorder()
c.ServeHTTP(rw, httptest.NewRequest(http.MethodGet, testUrl+"?queryParam=1", nil))
if state := rw.Header().Get("Cache-Status"); state != "miss" {
t.Errorf("unexpected cache state: want \"miss\", got: %q", state)
}

rw = httptest.NewRecorder()
c.ServeHTTP(rw, httptest.NewRequest(http.MethodGet, testUrl+"?queryParam=2", nil))
if state := rw.Header().Get("Cache-Status"); state != "miss" {
t.Errorf("unexpected cache state: want \"miss\", got: %q", state)
}
}

Expand Down