From 42219b546659579117bd9ce00148d80ca062c79f Mon Sep 17 00:00:00 2001 From: gyula Date: Fri, 19 Feb 2021 09:57:04 +0100 Subject: [PATCH] adding QueryMapArr --- context.go | 30 ++++++++++++++++++++++++++++++ context_test.go | 6 +++++- 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/context.go b/context.go index 3d6b56d6..9182a119 100644 --- a/context.go +++ b/context.go @@ -463,6 +463,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) string { @@ -552,6 +566,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 8e1e3b57..fd4c0e09 100644 --- a/context_test.go +++ b/context_test.go @@ -441,7 +441,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")) @@ -531,6 +531,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.Equal(t, 0, len(dicts)) }