From 371331ef11ebe4736a4061146cf8a95423f79263 Mon Sep 17 00:00:00 2001 From: lihainuo Date: Sat, 5 Sep 2026 19:11:14 +0800 Subject: [PATCH] fix(context): prevent nil pointer dereference in Cookie when Request is nil Context.Cookie panics with a nil pointer dereference when called on a Context without an http.Request (e.g. created via CreateTestContext). This is inconsistent with the query getters, which were made nil-safe (initQueryCache guard + TestContextDefaultQueryOnEmptyRequest), and with the binding layer, which rejects a nil request with an error (binding/json.go). A request-less context has no cookies, so return ("", http.ErrNoCookie), the same error the standard library reports when the named cookie is absent. Same bug class as #4772 (PostForm getters on nil request), but Cookie dereferences c.Request directly and is not covered by the initFormCache guard proposed in the #4772 pull requests. --- context.go | 5 +++++ context_test.go | 9 +++++++++ 2 files changed, 14 insertions(+) diff --git a/context.go b/context.go index 1dc730e3..620fc97d 100644 --- a/context.go +++ b/context.go @@ -1190,6 +1190,11 @@ func (c *Context) SetCookieData(cookie *http.Cookie) { // If multiple cookies match the given name, only one cookie will // be returned. func (c *Context) Cookie(name string) (string, error) { + // A nil Request (e.g. Context from CreateTestContext) has no cookies: + // report the same error as a request without the named cookie. + if c.Request == nil { + return "", http.ErrNoCookie + } cookie, err := c.Request.Cookie(name) if err != nil { return "", err diff --git a/context_test.go b/context_test.go index e8d305e4..27f8c3fc 100644 --- a/context_test.go +++ b/context_test.go @@ -903,6 +903,15 @@ func TestContextDefaultQueryOnEmptyRequest(t *testing.T) { }) } +func TestContextCookieWithNilRequest(t *testing.T) { + c, _ := CreateTestContext(httptest.NewRecorder()) // here c.Request == nil + assert.NotPanics(t, func() { + value, err := c.Cookie("NoCookie") + assert.Empty(t, value) + assert.ErrorIs(t, err, http.ErrNoCookie) + }) +} + func TestContextQueryAndPostForm(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) body := strings.NewReader("foo=bar&page=11&both=&foo=second")