From 34368955d0900c159682c49adee81688d166461b Mon Sep 17 00:00:00 2001 From: Siddh2024 Date: Fri, 5 Jun 2026 19:41:40 +0530 Subject: [PATCH] fix: handle non-positive timeout and nil cancel in RequestTimeoutMiddleware - When timeout <= 0, use the existing context directly instead of calling context.WithTimeout with a non-positive duration (which cancels immediately). - When an earlier deadline is kept, assign a no-op cancel func so defer cancel() does not panic on a nil function call. Fixes AnkanMisra/MicroAI-Paygate#196 --- gateway/middleware.go | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/gateway/middleware.go b/gateway/middleware.go index 652bc33..e949259 100644 --- a/gateway/middleware.go +++ b/gateway/middleware.go @@ -161,8 +161,10 @@ func RequestTimeoutMiddleware(timeout time.Duration) gin.HandlerFunc { var cancel context.CancelFunc var ctx context.Context if timeout <= 0 { - // Preserve the existing behavior for zero/negative values. - ctx, cancel = context.WithTimeout(c.Request.Context(), timeout) + // Zero/negative timeout means no timeout — use the existing context + // without wrapping it, so requests don't cancel immediately. + ctx = c.Request.Context() + cancel = func() {} // no-op to avoid nil cancel panic in defer } else { if d, ok := c.Request.Context().Deadline(); ok { desired := time.Now().Add(timeout) @@ -170,6 +172,7 @@ func RequestTimeoutMiddleware(timeout time.Duration) gin.HandlerFunc { // a new deadline at the desired point. if d.Before(desired) { ctx = c.Request.Context() + cancel = func() {} // no-op to avoid nil cancel panic in defer } else { ctx, cancel = context.WithDeadline(c.Request.Context(), desired) } @@ -177,9 +180,7 @@ func RequestTimeoutMiddleware(timeout time.Duration) gin.HandlerFunc { ctx, cancel = context.WithTimeout(c.Request.Context(), timeout) } } - if cancel != nil { - defer cancel() - } + defer cancel() c.Request = c.Request.WithContext(ctx) origWriter := c.Writer