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
This commit is contained in:
RubenPari 2026-08-08 11:06:23 +02:00
parent 34dac209ff
commit 0aae1ab6c9
2 changed files with 31 additions and 4 deletions

View File

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

View File

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