diff --git a/context.go b/context.go index 1f356515..08976e96 100644 --- a/context.go +++ b/context.go @@ -644,6 +644,20 @@ func (c *Context) GetQueryMap(key string) (map[string]string, bool) { return c.get(c.queryCache, key) } +// QueryMapArray returns a map for a given query key. +// Same as QueryMap, but the value in the map is an array +func (c *Context) QueryMapArray(key string) map[string][]string { + dicts, _ := c.GetQueryMapArray(key) + return dicts +} + +// GetQueryMapArray returns a map for a given query key, plus a boolean value +// whether at least one value exists for the given key. +func (c *Context) GetQueryMapArray(key string) (map[string][]string, bool) { + c.initQueryCache() + return c.getarr(c.queryCache, key) +} + // PostForm returns the specified key from a POST urlencoded form or multipart form // when it exists, otherwise it returns an empty string `("")`. func (c *Context) PostForm(key string) (value string) { @@ -732,6 +746,22 @@ func (c *Context) get(m map[string][]string, key string) (map[string]string, boo return dicts, exist } +// getarr is an internal method. same as get, but the value in the map is an array +// since get only returns the first value +func (c *Context) getarr(m map[string][]string, key string) (map[string][]string, bool) { + dicts := make(map[string][]string) + exist := false + for k, v := range m { + if i := strings.IndexByte(k, '['); i >= 1 && k[0:i] == key { + if j := strings.IndexByte(k[i+1:], ']'); j >= 1 { + exist = true + dicts[k[i+1:][:j]] = v + } + } + } + return dicts, exist +} + // FormFile returns the first file for the provided form key. func (c *Context) FormFile(name string) (*multipart.FileHeader, error) { if c.Request.MultipartForm == nil { diff --git a/context_test.go b/context_test.go index 211fbb1b..cef168f6 100644 --- a/context_test.go +++ b/context_test.go @@ -632,7 +632,7 @@ func TestContextQueryAndPostForm(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) body := bytes.NewBufferString("foo=bar&page=11&both=&foo=second") c.Request, _ = http.NewRequest("POST", - "/?both=GET&id=main&id=omit&array[]=first&array[]=second&ids[a]=hi&ids[b]=3.14", body) + "/?both=GET&id=main&id=omit&array[]=first&array[]=second&ids[a]=hi&ids[b]=3.14&filter[t]=hi&filter[t]=hello", body) c.Request.Header.Add("Content-Type", MIMEPOSTForm) assert.Equal(t, "bar", c.DefaultPostForm("foo", "none")) @@ -722,6 +722,10 @@ func TestContextQueryAndPostForm(t *testing.T) { assert.Equal(t, "hi", dicts["a"]) assert.Equal(t, "3.14", dicts["b"]) + maparr := c.QueryMapArray("filter") + assert.Equal(t, "hi", maparr["t"][0]) + assert.Equal(t, "hello", maparr["t"][1]) + dicts = c.QueryMap("nokey") assert.Empty(t, dicts) }