diff --git a/context.go b/context.go index 788b00bb..389658e1 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 cef488c9..2c87c002 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")