mirror of
https://github.com/gin-gonic/gin.git
synced 2026-09-04 14:49:27 +08:00
Merge a010fc44ae00a76cecc9800a994f9ca552bb4873 into dcaa4296d111981ffb31ac3eba90bb63e1eb5ab9
This commit is contained in:
commit
a2023fcadb
15
context.go
15
context.go
@ -648,13 +648,18 @@ func (c *Context) PostFormArray(key string) (values []string) {
|
||||
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 c.Request != nil {
|
||||
var maxMemory int64 = defaultMultipartMemory
|
||||
if c.engine != nil {
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -3955,3 +3955,43 @@ func BenchmarkGetMapFromFormData(b *testing.B) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestContextPostFormWithoutRequest(t *testing.T) {
|
||||
// Case 1: c.Request is nil, c.engine is nil
|
||||
c1 := &Context{}
|
||||
val, ok := c1.GetPostForm("key")
|
||||
assert.False(t, ok)
|
||||
assert.Empty(t, val)
|
||||
assert.Empty(t, c1.PostForm("key"))
|
||||
assert.Equal(t, "default_val", c1.DefaultPostForm("key", "default_val"))
|
||||
assert.Empty(t, c1.PostFormArray("key"))
|
||||
assert.Empty(t, c1.PostFormMap("key"))
|
||||
|
||||
// Case 2: c.Request is nil, c.engine is not nil
|
||||
c2, _ := CreateTestContext(httptest.NewRecorder())
|
||||
c2.Request = nil
|
||||
val, ok = c2.GetPostForm("key")
|
||||
assert.False(t, ok)
|
||||
assert.Empty(t, val)
|
||||
assert.Empty(t, c2.PostForm("key"))
|
||||
assert.Equal(t, "default_val", c2.DefaultPostForm("key", "default_val"))
|
||||
assert.Empty(t, c2.PostFormArray("key"))
|
||||
assert.Empty(t, c2.PostFormMap("key"))
|
||||
|
||||
// Case 3: c.Request is not nil, c.engine is nil
|
||||
c3 := &Context{}
|
||||
req3, _ := http.NewRequest(http.MethodPost, "/", strings.NewReader("key=value3"))
|
||||
req3.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
c3.Request = req3
|
||||
val, ok = c3.GetPostForm("key")
|
||||
assert.True(t, ok)
|
||||
assert.Equal(t, "value3", val)
|
||||
|
||||
// Case 4: c.Request has multipart error, c.engine is nil
|
||||
c4 := &Context{}
|
||||
req4, _ := http.NewRequest(http.MethodPost, "/", strings.NewReader("bad multipart payload"))
|
||||
req4.Header.Set("Content-Type", "multipart/form-data; boundary=boundary")
|
||||
c4.Request = req4
|
||||
_, ok = c4.GetPostForm("key")
|
||||
assert.False(t, ok)
|
||||
}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user