From f23fb234f6fc6518a3ae67a4c39d4b2d4257f735 Mon Sep 17 00:00:00 2001 From: Farmerx Date: Mon, 29 Oct 2018 09:16:30 +0800 Subject: [PATCH] Update context.go # add A new method for parsing form data array type fields --- context.go | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/context.go b/context.go index c8a59bb0..f225c6a7 100644 --- a/context.go +++ b/context.go @@ -432,6 +432,48 @@ func (c *Context) PostFormMap(key string) map[string]string { return dicts } +// 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) {