adding QueryMapArr

This commit is contained in:
gyula 2021-02-19 09:57:04 +01:00
parent 1bdf86b722
commit 42219b5466
2 changed files with 35 additions and 1 deletions

View File

@ -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 {

View File

@ -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))
}