Support map as query string or post form parameters (#1383)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* support query map * add GetQueryMap and unittest * support post-form map * add readme for query map * attempt to fix bug for post-form map when go version is 1.6 * remove duplicate code * remove comment
authored by 田欧 · committed by Bo-Yi Wu · parent 631cfbd · Browse files · 3 files·+121 added−1 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+121 added−1 removed
- other:+121 added−1 removed
Provenance
- Commit
647535c- Tree
07c259a- Author
田欧 <thinkerou@gmail.com>- Committer
Bo-Yi Wu <appleboy.tw@gmail.com>- Parent
631cfbd
3 files changed+121 added−1 removed
modified:context_test.go+44 added-1 removed
45 unmodified lines46 must(mw.WriteField("id", ""))47 must(mw.WriteField("time_local", "31/12/2016 14:55"))48 must(mw.WriteField("time_utc", "31/12/2016 14:55"))49 must(mw.WriteField("time_location", "31/12/2016 14:55"))50+ must(mw.WriteField("names[a]", "thinkerou"))51+ must(mw.WriteField("names[b]", "tianou"))52 req, err := http.NewRequest("POST", "/", body)53 must(err)54 req.Header.Set("Content-Type", MIMEMultipartPOSTForm+"; boundary="+boundary)55 return req316 unmodified lines372 373 func TestContextQueryAndPostForm(t *testing.T) {374 c, _ := CreateTestContext(httptest.NewRecorder())375 body := bytes.NewBufferString("foo=bar&page=11&both=&foo=second")374- c.Request, _ = http.NewRequest("POST", "/?both=GET&id=main&id=omit&array[]=first&array[]=second", body)376+ c.Request, _ = http.NewRequest("POST",377+ "/?both=GET&id=main&id=omit&array[]=first&array[]=second&ids[a]=hi&ids[b]=3.14", body)378 c.Request.Header.Add("Content-Type", MIMEPOSTForm)379 380 assert.Equal(t, "bar", c.DefaultPostForm("foo", "none"))381 assert.Equal(t, "bar", c.PostForm("foo"))59 unmodified lines441 442 values = c.QueryArray("both")443 assert.Equal(t, 1, len(values))444 assert.Equal(t, "GET", values[0])445+446+ dicts, ok := c.GetQueryMap("ids")447+ assert.True(t, ok)448+ assert.Equal(t, "hi", dicts["a"])449+ assert.Equal(t, "3.14", dicts["b"])450+451+ dicts, ok = c.GetQueryMap("nokey")452+ assert.False(t, ok)453+ assert.Equal(t, 0, len(dicts))454+455+ dicts, ok = c.GetQueryMap("both")456+ assert.False(t, ok)457+ assert.Equal(t, 0, len(dicts))458+459+ dicts, ok = c.GetQueryMap("array")460+ assert.False(t, ok)461+ assert.Equal(t, 0, len(dicts))462+463+ dicts = c.QueryMap("ids")464+ assert.Equal(t, "hi", dicts["a"])465+ assert.Equal(t, "3.14", dicts["b"])466+467+ dicts = c.QueryMap("nokey")468+ assert.Equal(t, 0, len(dicts))469 }470 471 func TestContextPostFormMultipart(t *testing.T) {472 c, _ := CreateTestContext(httptest.NewRecorder())68 unmodified lines541 542 values = c.PostFormArray("foo")543 assert.Equal(t, 1, len(values))544 assert.Equal(t, "bar", values[0])545+546+ dicts, ok := c.GetPostFormMap("names")547+ assert.True(t, ok)548+ assert.Equal(t, "thinkerou", dicts["a"])549+ assert.Equal(t, "tianou", dicts["b"])550+551+ dicts, ok = c.GetPostFormMap("nokey")552+ assert.False(t, ok)553+ assert.Equal(t, 0, len(dicts))554+555+ dicts = c.PostFormMap("names")556+ assert.Equal(t, "thinkerou", dicts["a"])557+ assert.Equal(t, "tianou", dicts["b"])558+559+ dicts = c.PostFormMap("nokey")560+ assert.Equal(t, 0, len(dicts))561 }562 563 func TestContextSetCookie(t *testing.T) {564 c, _ := CreateTestContext(httptest.NewRecorder())996 unmodified linesmodified:context.go+48 added
358 unmodified lines359 }360 return []string{}, false361 }362 363+// QueryMap returns a map for a given query key.364+func (c *Context) QueryMap(key string) map[string]string {365+ dicts, _ := c.GetQueryMap(key)366+ return dicts367+}368+369+// GetQueryMap returns a map for a given query key, plus a boolean value370+// whether at least one value exists for the given key.371+func (c *Context) GetQueryMap(key string) (map[string]string, bool) {372+ return c.get(c.Request.URL.Query(), key)373+}374+375 // PostForm returns the specified key from a POST urlencoded form or multipart form376 // when it exists, otherwise it returns an empty string `("")`.377 func (c *Context) PostForm(key string) string {378 value, _ := c.GetPostForm(key)47 unmodified lines426 }427 return []string{}, false428 }429 430+// PostFormMap returns a map for a given form key.431+func (c *Context) PostFormMap(key string) map[string]string {432+ dicts, _ := c.GetPostFormMap(key)433+ return dicts434+}435+436+// GetPostFormMap returns a map for a given form key, plus a boolean value437+// whether at least one value exists for the given key.438+func (c *Context) GetPostFormMap(key string) (map[string]string, bool) {439+ req := c.Request440+ req.ParseForm()441+ req.ParseMultipartForm(c.engine.MaxMultipartMemory)442+ dicts, exist := c.get(req.PostForm, key)443+444+ if !exist && req.MultipartForm != nil && req.MultipartForm.File != nil {445+ dicts, exist = c.get(req.MultipartForm.Value, key)446+ }447+448+ return dicts, exist449+}450+451+// get is an internal method and returns a map which satisfy conditions.452+func (c *Context) get(m map[string][]string, key string) (map[string]string, bool) {453+ dicts := make(map[string]string)454+ exist := false455+ for k, v := range m {456+ if i := strings.IndexByte(k, '['); i >= 1 && k[0:i] == key {457+ if j := strings.IndexByte(k[i+1:], ']'); j >= 1 {458+ exist = true459+ dicts[k[i+1:][:j]] = v[0]460+ }461+ }462+ }463+ return dicts, exist464+}465+466 // FormFile returns the first file for the provided form key.467 func (c *Context) FormFile(name string) (*multipart.FileHeader, error) {468 _, fh, err := c.Request.FormFile(name)469 return fh, err464 unmodified linesmodified:README.md+29 added
25 unmodified lines26 - [Parameters in path](#parameters-in-path)27 - [Querystring parameters](#querystring-parameters)28 - [Multipart/Urlencoded Form](#multiparturlencoded-form)29 - [Another example: query + post form](#another-example-query--post-form)30+ - [Map as querystring or postform parameters](#map-as-querystring-or-postform-parameters)31 - [Upload files](#upload-files)32 - [Grouping routes](#grouping-routes)33 - [Blank Gin without middleware by default](#blank-gin-without-middleware-by-default)34 - [Using middleware](#using-middleware)288 unmodified lines323 ```324 id: 1234; page: 1; name: manu; message: this_is_great325 ```326 327+### Map as querystring or postform parameters328+329+```330+POST /post?ids[a]=1234&ids[b]=hello HTTP/1.1331+Content-Type: application/x-www-form-urlencoded332+333+names[first]=thinkerou&names[second]=tianou334+```335+336+```go337+func main() {338+ router := gin.Default()339+340+ router.POST("/post", func(c *gin.Context) {341+342+ ids := c.QueryMap("ids")343+ names := c.PostFormMap("names")344+345+ fmt.Printf("ids: %v; names: %v", ids, names)346+ })347+ router.Run(":8080")348+}349+```350+351+```352+ids: map[b:hello a:1234], names: map[second:tianou first:thinkerou]353+```354+355 ### Upload files356 357 #### Single file358 1461 unmodified lines