mirror of
https://github.com/gin-gonic/gin.git
synced 2026-11-23 11:33:37 +08:00
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:
parent
34dac209ff
commit
0aae1ab6c9
10
context.go
10
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
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -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")
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user