📦 feat: method QueryParser in context

pull/585/head
renanbastos93 2020-07-10 18:28:18 -03:00
parent 89493f5565
commit 4470d77295
2 changed files with 57 additions and 0 deletions

18
ctx.go
View File

@ -257,6 +257,7 @@ func (ctx *Ctx) BodyParser(out interface{}) error {
}
// query params
if ctx.Fasthttp.QueryArgs().Len() > 0 {
log.Println("Converting querystring using BodyParser will be deprecated, please use ctx.QueryParser")
data := make(map[string][]string)
ctx.Fasthttp.QueryArgs().VisitAll(func(key []byte, val []byte) {
data[getString(key)] = append(data[getString(key)], getString(val))
@ -267,6 +268,23 @@ func (ctx *Ctx) BodyParser(out interface{}) error {
return fmt.Errorf("bodyparser: cannot parse content-type: %v", ctype)
}
// QueryParser binds the query string to a struct.
func (ctx *Ctx) QueryParser(out interface{}) error {
if ctx.Fasthttp.QueryArgs().Len() > 0 {
var schemaDecoderQuery = schema.NewDecoder()
schemaDecoderQuery.SetAliasTag("query")
schemaDecoderQuery.IgnoreUnknownKeys(true)
data := make(map[string][]string)
ctx.Fasthttp.QueryArgs().VisitAll(func(key []byte, val []byte) {
data[getString(key)] = append(data[getString(key)], getString(val))
})
return schemaDecoderQuery.Decode(out, data)
}
return nil
}
// ClearCookie expires a specific cookie by key on the client side.
// If no key is provided it expires all cookies that came with the request.
func (ctx *Ctx) ClearCookie(key ...string) {

View File

@ -1531,3 +1531,42 @@ func Benchmark_Ctx_SendBytes_B(b *testing.B) {
}
utils.AssertEqual(b, []byte("Hello, world!"), c.Fasthttp.Response.Body())
}
func Test_Ctx_QueryParser(t *testing.T) {
t.Parallel()
app := New()
ctx := app.AcquireCtx(&fasthttp.RequestCtx{})
defer app.ReleaseCtx(ctx)
type Query struct {
ID int
Name string
Hobby []string
}
ctx.Fasthttp.Request.SetBody([]byte(``))
ctx.Fasthttp.Request.Header.SetContentType("")
ctx.Fasthttp.Request.URI().SetQueryString("id=1&name=tom&hobby=basketball&hobby=football")
q := new(Query)
utils.AssertEqual(t, nil, ctx.QueryParser(q))
utils.AssertEqual(t, 2, len(q.Hobby))
}
func Benchmark_Ctx_QueryParser(b *testing.B) {
app := New()
ctx := app.AcquireCtx(&fasthttp.RequestCtx{})
defer app.ReleaseCtx(ctx)
type Query struct {
ID int
Name string
Hobby []string
}
ctx.Fasthttp.Request.SetBody([]byte(``))
ctx.Fasthttp.Request.Header.SetContentType("")
ctx.Fasthttp.Request.URI().SetQueryString("id=1&name=tom&hobby=basketball&hobby=football")
q := new(Query)
b.ReportAllocs()
b.ResetTimer()
for n := 0; n < b.N; n++ {
ctx.QueryParser(q)
}
utils.AssertEqual(b, nil, ctx.QueryParser(q))
}