From 5e4cf1fde80b2f186544727ed02224e6b9a44dfb Mon Sep 17 00:00:00 2001 From: Virgil Date: Thu, 2 Apr 2026 08:34:09 +0000 Subject: [PATCH] refactor(api): clarify cache limits api Co-Authored-By: Virgil --- cache_test.go | 2 +- options.go | 31 ++++++++++++++++++++++--------- 2 files changed, 23 insertions(+), 10 deletions(-) diff --git a/cache_test.go b/cache_test.go index aec4989..309e966 100644 --- a/cache_test.go +++ b/cache_test.go @@ -488,7 +488,7 @@ func TestWithCache_Good_EvictsWhenCapacityReached(t *testing.T) { func TestWithCache_Good_EvictsWhenSizeLimitReached(t *testing.T) { gin.SetMode(gin.TestMode) grp := &cacheSizedGroup{} - e, _ := api.New(api.WithCache(5*time.Second, 10, 250)) + e, _ := api.New(api.WithCacheLimits(5*time.Second, 10, 250)) e.Register(grp) h := e.Handler() diff --git a/options.go b/options.go index 3b3071f..4c61289 100644 --- a/options.go +++ b/options.go @@ -504,19 +504,32 @@ func timeoutResponse(c *gin.Context) { // // engine, _ := api.New(api.WithCache(5*time.Minute, 100, 10<<20)) func WithCache(ttl time.Duration, maxEntries ...int) Option { + entryLimit := 0 + byteLimit := 0 + if len(maxEntries) > 0 { + entryLimit = maxEntries[0] + } + if len(maxEntries) > 1 { + byteLimit = maxEntries[1] + } + return WithCacheLimits(ttl, entryLimit, byteLimit) +} + +// WithCacheLimits adds in-memory response caching middleware for GET requests +// with explicit entry and payload-size bounds. +// +// This is the clearer form of WithCache when call sites want to make the +// eviction policy self-documenting. +// +// Example: +// +// engine, _ := api.New(api.WithCacheLimits(5*time.Minute, 100, 10<<20)) +func WithCacheLimits(ttl time.Duration, maxEntries, maxBytes int) Option { return func(e *Engine) { if ttl <= 0 { return } - entryLimit := 0 - byteLimit := 0 - if len(maxEntries) > 0 { - entryLimit = maxEntries[0] - } - if len(maxEntries) > 1 { - byteLimit = maxEntries[1] - } - store := newCacheStore(entryLimit, byteLimit) + store := newCacheStore(maxEntries, maxBytes) e.middlewares = append(e.middlewares, cacheMiddleware(store, ttl)) } }