Skip to content
Myr

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

3 files+121 added−1 removed

modified:context_test.go+44 added-1 removed
45 unmodified lines
46 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 req
316 unmodified lines
372373func 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)379380 assert.Equal(t, "bar", c.DefaultPostForm("foo", "none"))381 assert.Equal(t, "bar", c.PostForm("foo"))
59 unmodified lines
441442 values = c.QueryArray("both")443 assert.Equal(t, 1, len(values))444 assert.Equal(t, "GET", values[0])445446 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"])450451 dicts, ok = c.GetQueryMap("nokey")452 assert.False(t, ok)453 assert.Equal(t, 0, len(dicts))454455 dicts, ok = c.GetQueryMap("both")456 assert.False(t, ok)457 assert.Equal(t, 0, len(dicts))458459 dicts, ok = c.GetQueryMap("array")460 assert.False(t, ok)461 assert.Equal(t, 0, len(dicts))462463 dicts = c.QueryMap("ids")464 assert.Equal(t, "hi", dicts["a"])465 assert.Equal(t, "3.14", dicts["b"])466467 dicts = c.QueryMap("nokey")468 assert.Equal(t, 0, len(dicts))469}470471func TestContextPostFormMultipart(t *testing.T) {472 c, _ := CreateTestContext(httptest.NewRecorder())
68 unmodified lines
541542 values = c.PostFormArray("foo")543 assert.Equal(t, 1, len(values))544 assert.Equal(t, "bar", values[0])545546 dicts, ok := c.GetPostFormMap("names")547 assert.True(t, ok)548 assert.Equal(t, "thinkerou", dicts["a"])549 assert.Equal(t, "tianou", dicts["b"])550551 dicts, ok = c.GetPostFormMap("nokey")552 assert.False(t, ok)553 assert.Equal(t, 0, len(dicts))554555 dicts = c.PostFormMap("names")556 assert.Equal(t, "thinkerou", dicts["a"])557 assert.Equal(t, "tianou", dicts["b"])558559 dicts = c.PostFormMap("nokey")560 assert.Equal(t, 0, len(dicts))561}562563func TestContextSetCookie(t *testing.T) {564 c, _ := CreateTestContext(httptest.NewRecorder())
996 unmodified lines
modified:context.go+48 added
358 unmodified lines
359 }360 return []string{}, false361}362363// QueryMap returns a map for a given query key.364func (c *Context) QueryMap(key string) map[string]string {365 dicts, _ := c.GetQueryMap(key)366 return dicts367}368369// GetQueryMap returns a map for a given query key, plus a boolean value370// whether at least one value exists for the given key.371func (c *Context) GetQueryMap(key string) (map[string]string, bool) {372 return c.get(c.Request.URL.Query(), key)373}374375// PostForm returns the specified key from a POST urlencoded form or multipart form376// when it exists, otherwise it returns an empty string `("")`.377func (c *Context) PostForm(key string) string {378 value, _ := c.GetPostForm(key)
47 unmodified lines
426 }427 return []string{}, false428}429430// PostFormMap returns a map for a given form key.431func (c *Context) PostFormMap(key string) map[string]string {432 dicts, _ := c.GetPostFormMap(key)433 return dicts434}435436// GetPostFormMap returns a map for a given form key, plus a boolean value437// whether at least one value exists for the given key.438func (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)443444 if !exist && req.MultipartForm != nil && req.MultipartForm.File != nil {445 dicts, exist = c.get(req.MultipartForm.Value, key)446 }447448 return dicts, exist449}450451// get is an internal method and returns a map which satisfy conditions.452func (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}465466// FormFile returns the first file for the provided form key.467func (c *Context) FormFile(name string) (*multipart.FileHeader, error) {468 _, fh, err := c.Request.FormFile(name)469 return fh, err
464 unmodified lines
modified:README.md+29 added
25 unmodified lines
26 - [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 lines
323```324id: 1234; page: 1; name: manu; message: this_is_great325```326327### Map as querystring or postform parameters328329```330POST /post?ids[a]=1234&ids[b]=hello HTTP/1.1331Content-Type: application/x-www-form-urlencoded332333names[first]=thinkerou&names[second]=tianou334```335336```go337func main() {338 router := gin.Default()339340 router.POST("/post", func(c *gin.Context) {341342 ids := c.QueryMap("ids")343 names := c.PostFormMap("names")344345 fmt.Printf("ids: %v; names: %v", ids, names)346 })347 router.Run(":8080")348}349```350351```352ids: map[b:hello a:1234], names: map[second:tianou first:thinkerou]353```354355### Upload files356357#### Single file358
1461 unmodified lines