add an example for #1659

This commit is contained in:
Gerasimos (Makis) Maropoulos 2020-10-18 19:37:33 +03:00
parent 637f7aeea7
commit 7ab51805ba
No known key found for this signature in database
GPG Key ID: 5DBE766BD26A54E7
4 changed files with 60 additions and 2 deletions

View File

@ -168,8 +168,9 @@
* [Bind Form](request-body/read-form/main.go)
* [Checkboxes](request-body/read-form/checkboxes/main.go)
* [Bind Query](request-body/read-query/main.go)
* [Bind Headers](request-body/read-headers/main.go)
* [Bind Params](request-body/read-params/main.go)
* [Bind URL](request-body/read-url/main.go)
* [Bind Headers](request-body/read-headers/main.go)
* [Bind Body](request-body/read-body/main.go)
* [Bind Custom per type](request-body/read-custom-per-type/main.go)
* [Bind Custom via Unmarshaler](request-body/read-custom-via-unmarshaler/main.go)

View File

@ -0,0 +1,38 @@
// package main contains an example on how to use the ReadParams,
// same way you can do the ReadQuery, ReadJSON, ReadProtobuf and e.t.c.
package main
import (
"github.com/kataras/iris/v12"
)
type myURL struct {
Name string `url:"name"` // or `param:"name"`
Age int `url:"age"` // >> >>
Tail []string `url:"tail"` // >> >>
}
func main() {
app := newApp()
// http://localhost:8080/iris/web/framework?name=kataras&age=27
// myURL: main.myURL{Name:"kataras", Age:27, Tail:[]string{"iris", "web", "framework"}}
app.Listen(":8080")
}
func newApp() *iris.Application {
app := iris.New()
app.Get("/{tail:path}", func(ctx iris.Context) {
var u myURL
// ReadURL is a shortcut of ReadParams + ReadQuery.
if err := ctx.ReadURL(&u); err != nil {
ctx.StopWithError(iris.StatusInternalServerError, err)
return
}
ctx.Writef("myURL: %#v", u)
})
return app
}

View File

@ -0,0 +1,16 @@
package main
import (
"testing"
"github.com/kataras/iris/v12/httptest"
)
func TestReadURL(t *testing.T) {
app := newApp()
e := httptest.New(t, app)
expectedBody := `myURL: main.myURL{Name:"kataras", Age:27, Tail:[]string{"iris", "web", "framework"}}`
e.GET("/iris/web/framework").WithQuery("name", "kataras").WithQuery("age", 27).Expect().Status(httptest.StatusOK).Body().Equal(expectedBody)
}

View File

@ -2363,7 +2363,10 @@ func (ctx *Context) ReadParams(ptr interface{}) error {
// It binds dynamic path parameters and URL query parameters
// to the "ptr" pointer struct value.
// The struct fields may contain "url" or "param" binding tags.
// If a validator exists then it validates the result too.
// If a validator exists then it validates the result too.
//
// Note that if the registered route contains a tail path parameter
// it may override any URL queries.
func (ctx *Context) ReadURL(ptr interface{}) error {
values := make(map[string][]string, ctx.params.Len())
ctx.params.Visit(func(key string, value string) {