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.
This commit is contained in:
lihainuo 2026-09-05 19:11:14 +08:00
parent dcaa4296d1
commit 371331ef11
2 changed files with 14 additions and 0 deletions

View File

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

View File

@ -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")