fix(api): disable cache middleware for non-positive ttl

Co-Authored-By: Virgil <virgil@lethean.io>
This commit is contained in:
Virgil 2026-04-01 23:09:12 +00:00
parent 29324b0a0b
commit 06f2263b73
2 changed files with 29 additions and 0 deletions

View file

@ -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{}

View file

@ -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]