diff --git a/context.go b/context.go index baa4b0f9..23621fdf 100644 --- a/context.go +++ b/context.go @@ -570,6 +570,48 @@ func (c *Context) PostFormMap(key string) (dicts map[string]string) { return } +// GetPostFormArrayMap returns a map for a given form key, plus a boolean value +// whether at least one value exists for the given key. +func (c *Context) GetPostFormArrayMap(key string) ([]map[string]string, bool) { + req := c.Request + req.ParseForm() + req.ParseMultipartForm(c.engine.MaxMultipartMemory) + dicts, exist := c.getArrayMap(req.PostForm, key) + if !exist && req.MultipartForm != nil && req.MultipartForm.File != nil { + dicts, exist = c.getArrayMap(req.MultipartForm.Value, key) + } + return dicts, exist +} + +// get is an internal method and returns a map which satisfy conditions. +func (c *Context) getArrayMap(m map[string][]string, key string) ([]map[string]string, bool) { + dicts := make(map[string]map[string]string) + exist := false + for k, v := range m { + if i := strings.IndexByte(k, '['); i >= 1 && k[0:i] == key { // 确定name[1]key + num := `` + if j := strings.IndexByte(k[i+1:], ']'); j >= 1 { + num = k[i+1:][:j] + } + if j := strings.IndexByte(k[i+1:], '['); j >= 1 { + exist = true + field := k[i+1:][j+1 : len(k[i+1:])-1] + if dict, ok := dicts[num]; ok { + dict[field] = v[0] + dicts[num] = dict + } else { + dicts[num] = map[string]string{field: v[0]} + } + } + } + } + arr := make([]map[string]string, 0) + for _, value := range dicts { + arr = append(arr, value) + } + return arr, exist +} + // GetPostFormMap returns a map for a given form key, plus a boolean value // whether at least one value exists for the given key. func (c *Context) GetPostFormMap(key string) (map[string]string, bool) { diff --git a/context_test.go b/context_test.go index 8bbf2700..518d4c59 100644 --- a/context_test.go +++ b/context_test.go @@ -58,6 +58,9 @@ func createMultipartRequest() *http.Request { must(mw.WriteField("time_location", "31/12/2016 14:55")) must(mw.WriteField("names[a]", "thinkerou")) must(mw.WriteField("names[b]", "tianou")) + must(mw.WriteField("array_map[0][a]", "test a")) + must(mw.WriteField("array_map[0][b]", "test b")) + req, err := http.NewRequest("POST", "/", body) must(err) req.Header.Set("Content-Type", MIMEMultipartPOSTForm+"; boundary="+boundary) @@ -669,6 +672,15 @@ func TestContextPostFormMultipart(t *testing.T) { dicts = c.PostFormMap("nokey") assert.Equal(t, 0, len(dicts)) + + arrayOfDict, ok := c.GetPostFormArrayMap("array_map") + assert.True(t, ok) + assert.Equal(t, "test a", arrayOfDict[0]["a"]) + assert.Equal(t, "test b", arrayOfDict[0]["b"]) + + arrayOfDict, ok = c.GetPostFormArrayMap("array_map_fail") + assert.False(t, ok) + } func TestContextSetCookie(t *testing.T) {