Skip to content

Commit

Permalink
Merge pull request #40 from joripage/cache-strategy-for-CacheByReques…
Browse files Browse the repository at this point in the history
…tURI

use WithCacheStrategyByRequest for CacheByRequestURI
  • Loading branch information
chenyahui authored May 17, 2024
2 parents 406f5aa + 5795247 commit fd2780f
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
4 changes: 4 additions & 0 deletions cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
25 changes: 25 additions & 0 deletions cache_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}

0 comments on commit fd2780f

Please sign in to comment.