From 06f2263b73b7c1113dc3d012f91cb49952600481 Mon Sep 17 00:00:00 2001 From: Virgil Date: Wed, 1 Apr 2026 23:09:12 +0000 Subject: [PATCH] fix(api): disable cache middleware for non-positive ttl Co-Authored-By: Virgil --- cache_test.go | 25 +++++++++++++++++++++++++ options.go | 4 ++++ 2 files changed, 29 insertions(+) diff --git a/cache_test.go b/cache_test.go index 1c05f22..4b0f64b 100644 --- a/cache_test.go +++ b/cache_test.go @@ -327,6 +327,31 @@ func TestWithCache_Good_PreservesCurrentRequestMetaOnHit(t *testing.T) { } } +func TestWithCache_Ugly_NonPositiveTTLDisablesMiddleware(t *testing.T) { + gin.SetMode(gin.TestMode) + grp := &cacheCounterGroup{} + e, _ := api.New(api.WithCache(0)) + e.Register(grp) + + h := e.Handler() + + for i := 0; i < 2; i++ { + w := httptest.NewRecorder() + req, _ := http.NewRequest(http.MethodGet, "/cache/counter", nil) + h.ServeHTTP(w, req) + if w.Code != http.StatusOK { + t.Fatalf("expected request %d to succeed with disabled cache, got %d", i+1, w.Code) + } + if got := w.Header().Get("X-Cache"); got != "" { + t.Fatalf("expected no X-Cache header with disabled cache, got %q", got) + } + } + + if grp.counter.Load() != 2 { + t.Fatalf("expected counter=2 with disabled cache, got %d", grp.counter.Load()) + } +} + func TestWithCache_Good_ExpiredCacheMisses(t *testing.T) { gin.SetMode(gin.TestMode) grp := &cacheCounterGroup{} diff --git a/options.go b/options.go index 1487282..2d9efa3 100644 --- a/options.go +++ b/options.go @@ -307,12 +307,16 @@ func timeoutResponse(c *gin.Context) { // // An optional maxEntries limit enables LRU eviction when the cache reaches // capacity. A value <= 0 keeps the cache unbounded for backward compatibility. +// A non-positive TTL disables the middleware entirely. // // Example: // // engine, _ := api.New(api.WithCache(5*time.Minute, 100)) func WithCache(ttl time.Duration, maxEntries ...int) Option { return func(e *Engine) { + if ttl <= 0 { + return + } limit := 0 if len(maxEntries) > 0 { limit = maxEntries[0]