diff --git a/cache.go b/cache.go index 947749f..e1cb85d 100644 --- a/cache.go +++ b/cache.go @@ -80,9 +80,11 @@ func cache( respCache := &ResponseCache{} err := cacheStore.Get(cacheKey, &respCache) if err == nil { - replyWithCache(c, cfg, respCache) - cfg.hitCacheCallback(c) - return + if !cfg.onlyUpdateCache { + replyWithCache(c, cfg, respCache) + cfg.hitCacheCallback(c) + return + } } if err != persist.ErrCacheMiss { diff --git a/cache_test.go b/cache_test.go index e1eeb07..5029361 100644 --- a/cache_test.go +++ b/cache_test.go @@ -221,6 +221,24 @@ func TestCacheByRequestURIIgnoreOrder(t *testing.T) { assert.NotEqual(t, w3.Body, w1.Body) } +func TestCacheByRequestURIOnlyUpdateCache(t *testing.T) { + memoryStore := persist.NewMemoryStore(1 * time.Minute) + cacheURIMiddleware := CacheByRequestURI(memoryStore, 3*time.Second) + + w1 := mockHttpRequest(cacheURIMiddleware, "/cache?uid=u1", true) + w2 := mockHttpRequest(cacheURIMiddleware, "/cache?uid=u1", true) + assert.Equal(t, w1.Body, w2.Body) + + cacheURIMiddlewareOnlyUpdateCache := CacheByRequestURI(memoryStore, 3*time.Second, OnlyUpdateCache()) + + w3 := mockHttpRequest(cacheURIMiddlewareOnlyUpdateCache, "/cache?uid=u1", true) + w4 := mockHttpRequest(cacheURIMiddlewareOnlyUpdateCache, "/cache?uid=u1", true) + assert.NotEqual(t, w3.Body, w4.Body) + + w5 := mockHttpRequest(cacheURIMiddleware, "/cache?uid=u1", true) + assert.Equal(t, w5.Body, w4.Body) +} + const prefixKey = "#prefix#" func TestPrefixKey(t *testing.T) { diff --git a/option.go b/option.go index 47df4b1..b43c179 100644 --- a/option.go +++ b/option.go @@ -24,6 +24,7 @@ type Config struct { prefixKey string withoutHeader bool discardHeaders []string + onlyUpdateCache bool } func newConfigByOpts(opts ...Option) *Config { @@ -148,6 +149,12 @@ func IgnoreQueryOrder() Option { } } +func OnlyUpdateCache() Option { + return func(c *Config) { + c.onlyUpdateCache = true + } +} + // WithPrefixKey will prefix the key func WithPrefixKey(prefix string) Option { return func(c *Config) {