From ccb9bfce0c83736f25fa4ef5016d8ea4def1c975 Mon Sep 17 00:00:00 2001 From: tung Date: Thu, 16 May 2024 15:02:48 +0700 Subject: [PATCH 1/2] use WithCacheStrategyByRequest for CacheByRequestURI --- cache.go | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/cache.go b/cache.go index d1a0849..1417b26 100644 --- a/cache.go +++ b/cache.go @@ -137,6 +137,10 @@ func cache( func CacheByRequestURI(defaultCacheStore persist.CacheStore, defaultExpire time.Duration, opts ...Option) gin.HandlerFunc { cfg := newConfigByOpts(opts...) + if cfg.getCacheStrategyByRequest != nil { + return cache(defaultCacheStore, defaultExpire, cfg) + } + var cacheStrategy GetCacheStrategyByRequest if cfg.ignoreQueryOrder { cacheStrategy = func(c *gin.Context) (bool, Strategy) { From 579524782bd70afd550746112195c3344b7e917c Mon Sep 17 00:00:00 2001 From: tung Date: Fri, 17 May 2024 13:15:36 +0700 Subject: [PATCH 2/2] add TestCacheByRequestURICustomCacheStrategy --- cache_test.go | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/cache_test.go b/cache_test.go index 6d108d0..3f97d41 100644 --- a/cache_test.go +++ b/cache_test.go @@ -293,3 +293,28 @@ func TestCustomCacheStrategy(t *testing.T) { err := memoryStore.Get("custom_cache_key_1", &val) assert.Nil(t, err) } + +func TestCacheByRequestURICustomCacheStrategy(t *testing.T) { + const customKey = "CustomKey" + memoryStore := persist.NewMemoryStore(1 * time.Minute) + cacheURIMiddleware := CacheByRequestURI(memoryStore, 1*time.Second, WithCacheStrategyByRequest(func(c *gin.Context) (bool, Strategy) { + return true, Strategy{ + CacheKey: customKey, + CacheDuration: 2 * time.Second, + } + })) + + w1 := mockHttpRequest(cacheURIMiddleware, "/cache?uid=u1", true) + var val interface{} + err := memoryStore.Get(customKey, &val) + assert.Nil(t, err) + time.Sleep(1 * time.Second) + + w2 := mockHttpRequest(cacheURIMiddleware, "/cache?uid=u1", true) + assert.Equal(t, w1.Body, w2.Body) + assert.Equal(t, w1.Code, w2.Code) + time.Sleep(3 * time.Second) + + w3 := mockHttpRequest(cacheURIMiddleware, "/cache?uid=u1", true) + assert.NotEqual(t, w1.Body, w3.Body) +}