fix(context): prevent nil pointer dereference in initFormCache when Request is nil (fix #4772)

This commit is contained in:
张名锐 2026-08-28 19:51:17 +08:00
parent dcaa4296d1
commit d8d025ef01
2 changed files with 31 additions and 5 deletions

View File

@ -648,13 +648,18 @@ func (c *Context) PostFormArray(key string) (values []string) {
func (c *Context) initFormCache() { func (c *Context) initFormCache() {
if c.formCache == nil { if c.formCache == nil {
c.formCache = make(url.Values) c.formCache = make(url.Values)
req := c.Request if c.Request != nil {
if err := req.ParseMultipartForm(c.engine.MaxMultipartMemory); err != nil { var maxMemory int64 = defaultMultipartMemory
if !errors.Is(err, http.ErrNotMultipart) { if c.engine != nil {
debugPrint("error on parse multipart form array: %v", err) maxMemory = c.engine.MaxMultipartMemory
} }
if err := c.Request.ParseMultipartForm(maxMemory); err != nil {
if !errors.Is(err, http.ErrNotMultipart) {
debugPrint("error on parse multipart form array: %v", err)
}
}
c.formCache = c.Request.PostForm
} }
c.formCache = req.PostForm
} }
} }

View File

@ -3955,3 +3955,24 @@ func BenchmarkGetMapFromFormData(b *testing.B) {
}) })
} }
} }
func TestContextPostFormWithoutRequest(t *testing.T) {
c, _ := CreateTestContext(httptest.NewRecorder())
c.Request = nil
val, ok := c.GetPostForm("key")
assert.False(t, ok)
assert.Empty(t, val)
val = c.PostForm("key")
assert.Empty(t, val)
val = c.DefaultPostForm("key", "default_val")
assert.Equal(t, "default_val", val)
vals := c.PostFormArray("key")
assert.Empty(t, vals)
mapVals := c.PostFormMap("key")
assert.Empty(t, mapVals)
}