From 0aae1ab6c9f6fb777175aee6097be4b70588d494 Mon Sep 17 00:00:00 2001 From: RubenPari Date: Sat, 8 Aug 2026 11:06:23 +0200 Subject: [PATCH] fix(context): prevent nil pointer panic in PostForm getters when Request is nil initFormCache called req.ParseMultipartForm without checking whether c.Request is nil, causing a nil-pointer panic when PostForm, GetPostForm, DefaultPostForm, PostFormArray, GetPostFormArray, PostFormMap, or GetPostFormMap are called on a Context with no request (e.g. in tests created with CreateTestContext). initQueryCache already guards against this; initFormCache now does the same. Fixes #4772 --- context.go | 10 ++++++---- context_test.go | 25 +++++++++++++++++++++++++ 2 files changed, 31 insertions(+), 4 deletions(-) diff --git a/context.go b/context.go index 1dc730e3..bbb90254 100644 --- a/context.go +++ b/context.go @@ -649,12 +649,14 @@ func (c *Context) initFormCache() { if c.formCache == nil { c.formCache = make(url.Values) req := c.Request - if err := req.ParseMultipartForm(c.engine.MaxMultipartMemory); err != nil { - if !errors.Is(err, http.ErrNotMultipart) { - debugPrint("error on parse multipart form array: %v", err) + if req != nil { + if err := req.ParseMultipartForm(c.engine.MaxMultipartMemory); err != nil { + if !errors.Is(err, http.ErrNotMultipart) { + debugPrint("error on parse multipart form array: %v", err) + } } + c.formCache = req.PostForm } - c.formCache = req.PostForm } } diff --git a/context_test.go b/context_test.go index e8d305e4..7d35a441 100644 --- a/context_test.go +++ b/context_test.go @@ -903,6 +903,31 @@ func TestContextDefaultQueryOnEmptyRequest(t *testing.T) { }) } +func TestContextPostFormOnEmptyRequest(t *testing.T) { + c, _ := CreateTestContext(httptest.NewRecorder()) // here c.Request == nil + assert.NotPanics(t, func() { + value, ok := c.GetPostForm("NoKey") + assert.False(t, ok) + assert.Empty(t, value) + }) + assert.NotPanics(t, func() { + assert.Equal(t, "nada", c.DefaultPostForm("NoKey", "nada")) + }) + assert.NotPanics(t, func() { + assert.Empty(t, c.PostForm("NoKey")) + }) + assert.NotPanics(t, func() { + values, ok := c.GetPostFormArray("NoKey") + assert.False(t, ok) + assert.Empty(t, values) + }) + assert.NotPanics(t, func() { + dicts, ok := c.GetPostFormMap("NoKey") + assert.False(t, ok) + assert.Empty(t, dicts) + }) +} + func TestContextQueryAndPostForm(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) body := strings.NewReader("foo=bar&page=11&both=&foo=second")