support bind uri param (#1612)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* support bind uri (1) * uri binding successful run * fix vet warning: github.com/gin-gonic/gin/internal.Param composite literal uses unkeyed fields * fix code style * update function name * fix test function signature * add test for CanSet * update readme and add test case * remove internal.Params * add coverage * fix warning
authored by thinkerou · committed by Bo-Yi Wu · parent 7ec82ee · Browse files · 8 files·+158 added−31 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
8 files+158 added−31 removed
- other:+158 added−31 removed
Provenance
- Commit
521d06c- Tree
9d04497- Author
thinkerou <thinkerou@gmail.com>- Committer
Bo-Yi Wu <appleboy.tw@gmail.com>- Parent
7ec82ee
8 files changed+158 added−31 removed
modified:binding/binding_test.go+30 added
660 unmodified lines661 err := JSON.Bind(req, &obj)662 assert.Error(t, err)663 }664 665+func TestUriBinding(t *testing.T) {666+ b := Uri667+ assert.Equal(t, "uri", b.Name())668+669+ type Tag struct {670+ Name string `uri:"name"`671+ }672+ var tag Tag673+ m := make(map[string][]string)674+ m["name"] = []string{"thinkerou"}675+ assert.NoError(t, b.BindUri(m, &tag))676+ assert.Equal(t, "thinkerou", tag.Name)677+678+ type NotSupportStruct struct {679+ Name map[string]interface{} `uri:"name"`680+ }681+ var not NotSupportStruct682+ assert.Error(t, b.BindUri(m, ¬))683+ assert.Equal(t, "", not.Name)684+}685+686 func testFormBinding(t *testing.T, method, path, badPath, body, badBody string) {687 b := Form688 assert.Equal(t, "form", b.Name())689 562 unmodified lines1252 func requestWithBody(method, path, body string) (req *http.Request) {1253 req, _ = http.NewRequest(method, path, bytes.NewBufferString(body))1254 return1255 }1256+1257+func TestCanSet(t *testing.T) {1258+ type CanSetStruct struct {1259+ lowerStart string `form:"lower"`1260+ }1261+1262+ var c CanSetStruct1263+ assert.Nil(t, mapForm(&c, nil))1264+}modified:binding/binding.go+8 added
34 unmodified lines35 Binding36 BindBody([]byte, interface{}) error37 }38 39+// BindingUri adds BindUri method to Binding. BindUri is similar with Bind,40+// but it read the Params.41+type BindingUri interface {42+ Name() string43+ BindUri(map[string][]string, interface{}) error44+}45+46 // StructValidator is the minimal interface which needs to be implemented in47 // order for it to be used as the validator engine for ensuring the correctness48 // of the request. Gin provides a default implementation for this using49 // https://github.com/go-playground/validator/tree/v8.18.2.26 unmodified lines76 FormMultipart = formMultipartBinding{}77 ProtoBuf = protobufBinding{}78 MsgPack = msgpackBinding{}79 YAML = yamlBinding{}80+ Uri = uriBinding{}81 )82 83 // Default returns the appropriate Binding instance based on the HTTP method84 // and the content type.27 unmodified linesmodified:binding/form_mapping.go+9 added-1 removed
10 unmodified lines11 "strings"12 "time"13 )14 15+func mapUri(ptr interface{}, m map[string][]string) error {16+ return mapFormByTag(ptr, m, "uri")17+}18+19 func mapForm(ptr interface{}, form map[string][]string) error {20+ return mapFormByTag(ptr, form, "form")21+}22+23+func mapFormByTag(ptr interface{}, form map[string][]string, tag string) error {24 typ := reflect.TypeOf(ptr).Elem()25 val := reflect.ValueOf(ptr).Elem()26 for i := 0; i < typ.NumField(); i++ {27 typeField := typ.Field(i)2 unmodified lines30 continue31 }32 33 structFieldKind := structField.Kind()26- inputFieldName := typeField.Tag.Get("form")34+ inputFieldName := typeField.Tag.Get(tag)35 inputFieldNameList := strings.Split(inputFieldName, ",")36 inputFieldName = inputFieldNameList[0]37 var defaultValue string38 if len(inputFieldNameList) > 1 {179 unmodified linesadded:binding/uri.go+18 added
1+// Copyright 2018 Gin Core Team. All rights reserved.2+// Use of this source code is governed by a MIT style3+// license that can be found in the LICENSE file.4+5+package binding6+7+type uriBinding struct{}8+9+func (uriBinding) Name() string {10+ return "uri"11+}12+13+func (uriBinding) BindUri(m map[string][]string, obj interface{}) error {14+ if err := mapUri(obj, m); err != nil {15+ return err16+ }17+ return validate(obj)18+}modified:context.go+10 added-3 removed
572 unmodified lines573 func (c *Context) ShouldBindYAML(obj interface{}) error {574 return c.ShouldBindWith(obj, binding.YAML)575 }576 577+// ShouldBindUri binds the passed struct pointer using the specified binding engine.578+func (c *Context) ShouldBindUri(obj interface{}) error {579+ m := make(map[string][]string)580+ for _, v := range c.Params {581+ m[v.Key] = []string{v.Value}582+ }583+ return binding.Uri.BindUri(m, obj)584+}585+586 // ShouldBindWith binds the passed struct pointer using the specified binding engine.587 // See the binding package.588 func (c *Context) ShouldBindWith(obj interface{}, b binding.Binding) error {589 return b.Bind(c.Request, obj)3 unmodified lines593 // body into the context, and reuse when it is called again.594 //595 // NOTE: This method reads the body before binding. So you should use596 // ShouldBindWith for better performance if you need to call only once.588-func (c *Context) ShouldBindBodyWith(589- obj interface{}, bb binding.BindingBody,590-) (err error) {597+func (c *Context) ShouldBindBodyWith(obj interface{}, bb binding.BindingBody) (err error) {598 var body []byte599 if cb, ok := c.Get(BodyBytesKey); ok {600 if cbb, ok := cb.([]byte); ok {601 body = cbb374 unmodified linesmodified:githubapi_test.go+21 added
283 unmodified lines284 //{"PATCH", "/user/keys/:id"},285 {"DELETE", "/user/keys/:id"},286 }287 288+func TestShouldBindUri(t *testing.T) {289+ DefaultWriter = os.Stdout290+ router := Default()291+292+ type Person struct {293+ Name string `uri:"name"`294+ Id string `uri:"id"`295+ }296+ router.Handle("GET", "/rest/:name/:id", func(c *Context) {297+ var person Person298+ assert.NoError(t, c.ShouldBindUri(&person))299+ assert.True(t, "" != person.Name)300+ assert.True(t, "" != person.Id)301+ c.String(http.StatusOK, "ShouldBindUri test OK")302+ })303+304+ path, _ := exampleFromPath("/rest/:name/:id")305+ w := performRequest(router, "GET", path)306+ assert.Equal(t, "ShouldBindUri test OK", w.Body.String())307+}308+309 func githubConfigRouter(router *Engine) {310 for _, route := range githubAPI {311 router.Handle(route.method, route.path, func(c *Context) {312 output := make(map[string]string, len(c.Params)+1)99 unmodified linesmodified:README.md+35 added
37 unmodified lines38 - [Model binding and validation](#model-binding-and-validation)39 - [Custom Validators](#custom-validators)40 - [Only Bind Query String](#only-bind-query-string)41 - [Bind Query String or Post Data](#bind-query-string-or-post-data)42+ - [Bind Uri](#bind-uri)43 - [Bind HTML checkboxes](#bind-html-checkboxes)44 - [Multipart/Urlencoded binding](#multiparturlencoded-binding)45 - [XML, JSON, YAML and ProtoBuf rendering](#xml-json-yaml-and-protobuf-rendering)46 - [JSONP rendering](#jsonp)746 unmodified lines793 ```sh794 $ curl -X GET "localhost:8085/testing?name=appleboy&address=xyz&birthday=1992-03-15"795 ```796 797+### Bind Uri798+799+See the [detail information](https://github.com/gin-gonic/gin/issues/846).800+801+```go802+package main803+804+import "github.com/gin-gonic/gin"805+806+type Person struct {807+ ID string `uri:"id" binding:"required,uuid"`808+ Name string `uri:"name" binding:"required"`809+}810+811+func main() {812+ route := gin.Default()813+ route.GET("/:name/:id", func(c *gin.Context) {814+ var person Person815+ if err := c.ShouldBindUri(&person); err != nil {816+ c.JSON(400, gin.H{"msg": err})817+ return818+ }819+ c.JSON(200, gin.H{"name": person.Name, "uuid": person.ID})820+ })821+ route.Run(":8088")822+}823+```824+825+Test it with:826+```sh827+$ curl -v localhost:8088/thinkerou/987fbc97-4bed-5078-9f07-9141ba07c9f3828+$ curl -v localhost:8088/thinkerou/not-uuid829+```830+831 ### Bind HTML checkboxes832 833 See the [detail information](https://github.com/gin-gonic/gin/issues/129#issuecomment-124260092)834 1168 unmodified linesmodified:tree_test.go+27 added-27 removed
168 unmodified lines169 }170 171 checkRequests(t, tree, testRequests{172 {"/", false, "/", nil},173- {"/cmd/test/", false, "/cmd/:tool/", Params{Param{"tool", "test"}}},174- {"/cmd/test", true, "", Params{Param{"tool", "test"}}},175- {"/cmd/test/3", false, "/cmd/:tool/:sub", Params{Param{"tool", "test"}, Param{"sub", "3"}}},176- {"/src/", false, "/src/*filepath", Params{Param{"filepath", "/"}}},177- {"/src/some/file.png", false, "/src/*filepath", Params{Param{"filepath", "/some/file.png"}}},173+ {"/cmd/test/", false, "/cmd/:tool/", Params{Param{Key: "tool", Value: "test"}}},174+ {"/cmd/test", true, "", Params{Param{Key: "tool", Value: "test"}}},175+ {"/cmd/test/3", false, "/cmd/:tool/:sub", Params{Param{Key: "tool", Value: "test"}, Param{Key: "sub", Value: "3"}}},176+ {"/src/", false, "/src/*filepath", Params{Param{Key: "filepath", Value: "/"}}},177+ {"/src/some/file.png", false, "/src/*filepath", Params{Param{Key: "filepath", Value: "/some/file.png"}}},178 {"/search/", false, "/search/", nil},179- {"/search/someth!ng+in+ünìcodé", false, "/search/:query", Params{Param{"query", "someth!ng+in+ünìcodé"}}},180- {"/search/someth!ng+in+ünìcodé/", true, "", Params{Param{"query", "someth!ng+in+ünìcodé"}}},181- {"/user_gopher", false, "/user_:name", Params{Param{"name", "gopher"}}},182- {"/user_gopher/about", false, "/user_:name/about", Params{Param{"name", "gopher"}}},183- {"/files/js/inc/framework.js", false, "/files/:dir/*filepath", Params{Param{"dir", "js"}, Param{"filepath", "/inc/framework.js"}}},184- {"/info/gordon/public", false, "/info/:user/public", Params{Param{"user", "gordon"}}},185- {"/info/gordon/project/go", false, "/info/:user/project/:project", Params{Param{"user", "gordon"}, Param{"project", "go"}}},179+ {"/search/someth!ng+in+ünìcodé", false, "/search/:query", Params{Param{Key: "query", Value: "someth!ng+in+ünìcodé"}}},180+ {"/search/someth!ng+in+ünìcodé/", true, "", Params{Param{Key: "query", Value: "someth!ng+in+ünìcodé"}}},181+ {"/user_gopher", false, "/user_:name", Params{Param{Key: "name", Value: "gopher"}}},182+ {"/user_gopher/about", false, "/user_:name/about", Params{Param{Key: "name", Value: "gopher"}}},183+ {"/files/js/inc/framework.js", false, "/files/:dir/*filepath", Params{Param{Key: "dir", Value: "js"}, Param{Key: "filepath", Value: "/inc/framework.js"}}},184+ {"/info/gordon/public", false, "/info/:user/public", Params{Param{Key: "user", Value: "gordon"}}},185+ {"/info/gordon/project/go", false, "/info/:user/project/:project", Params{Param{Key: "user", Value: "gordon"}, Param{Key: "project", Value: "go"}}},186 })187 188 checkPriorities(t, tree)189 checkMaxParams(t, tree)18 unmodified lines208 209 unescape := true210 checkRequests(t, tree, testRequests{211 {"/", false, "/", nil},212- {"/cmd/test/", false, "/cmd/:tool/", Params{Param{"tool", "test"}}},213- {"/cmd/test", true, "", Params{Param{"tool", "test"}}},214- {"/src/some/file.png", false, "/src/*filepath", Params{Param{"filepath", "/some/file.png"}}},215- {"/src/some/file+test.png", false, "/src/*filepath", Params{Param{"filepath", "/some/file test.png"}}},216- {"/src/some/file++++%%%%test.png", false, "/src/*filepath", Params{Param{"filepath", "/some/file++++%%%%test.png"}}},217- {"/src/some/file%2Ftest.png", false, "/src/*filepath", Params{Param{"filepath", "/some/file/test.png"}}},218- {"/search/someth!ng+in+ünìcodé", false, "/search/:query", Params{Param{"query", "someth!ng in ünìcodé"}}},219- {"/info/gordon/project/go", false, "/info/:user/project/:project", Params{Param{"user", "gordon"}, Param{"project", "go"}}},220- {"/info/slash%2Fgordon", false, "/info/:user", Params{Param{"user", "slash/gordon"}}},221- {"/info/slash%2Fgordon/project/Project%20%231", false, "/info/:user/project/:project", Params{Param{"user", "slash/gordon"}, Param{"project", "Project #1"}}},222- {"/info/slash%%%%", false, "/info/:user", Params{Param{"user", "slash%%%%"}}},223- {"/info/slash%%%%2Fgordon/project/Project%%%%20%231", false, "/info/:user/project/:project", Params{Param{"user", "slash%%%%2Fgordon"}, Param{"project", "Project%%%%20%231"}}},212+ {"/cmd/test/", false, "/cmd/:tool/", Params{Param{Key: "tool", Value: "test"}}},213+ {"/cmd/test", true, "", Params{Param{Key: "tool", Value: "test"}}},214+ {"/src/some/file.png", false, "/src/*filepath", Params{Param{Key: "filepath", Value: "/some/file.png"}}},215+ {"/src/some/file+test.png", false, "/src/*filepath", Params{Param{Key: "filepath", Value: "/some/file test.png"}}},216+ {"/src/some/file++++%%%%test.png", false, "/src/*filepath", Params{Param{Key: "filepath", Value: "/some/file++++%%%%test.png"}}},217+ {"/src/some/file%2Ftest.png", false, "/src/*filepath", Params{Param{Key: "filepath", Value: "/some/file/test.png"}}},218+ {"/search/someth!ng+in+ünìcodé", false, "/search/:query", Params{Param{Key: "query", Value: "someth!ng in ünìcodé"}}},219+ {"/info/gordon/project/go", false, "/info/:user/project/:project", Params{Param{Key: "user", Value: "gordon"}, Param{Key: "project", Value: "go"}}},220+ {"/info/slash%2Fgordon", false, "/info/:user", Params{Param{Key: "user", Value: "slash/gordon"}}},221+ {"/info/slash%2Fgordon/project/Project%20%231", false, "/info/:user/project/:project", Params{Param{Key: "user", Value: "slash/gordon"}, Param{Key: "project", Value: "Project #1"}}},222+ {"/info/slash%%%%", false, "/info/:user", Params{Param{Key: "user", Value: "slash%%%%"}}},223+ {"/info/slash%%%%2Fgordon/project/Project%%%%20%231", false, "/info/:user/project/:project", Params{Param{Key: "user", Value: "slash%%%%2Fgordon"}, Param{Key: "project", Value: "Project%%%%20%231"}}},224 }, unescape)225 226 checkPriorities(t, tree)227 checkMaxParams(t, tree)97 unmodified lines325 326 checkRequests(t, tree, testRequests{327 {"/", false, "/", nil},328 {"/doc/", false, "/doc/", nil},329- {"/src/some/file.png", false, "/src/*filepath", Params{Param{"filepath", "/some/file.png"}}},330- {"/search/someth!ng+in+ünìcodé", false, "/search/:query", Params{Param{"query", "someth!ng+in+ünìcodé"}}},331- {"/user_gopher", false, "/user_:name", Params{Param{"name", "gopher"}}},329+ {"/src/some/file.png", false, "/src/*filepath", Params{Param{Key: "filepath", Value: "/some/file.png"}}},330+ {"/search/someth!ng+in+ünìcodé", false, "/search/:query", Params{Param{Key: "query", Value: "someth!ng+in+ünìcodé"}}},331+ {"/user_gopher", false, "/user_:name", Params{Param{Key: "name", Value: "gopher"}}},332 })333 }334 335 func TestEmptyWildcardName(t *testing.T) {362 unmodified lines