Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

🔥 Feature: add queryBool parser #2329

Merged
merged 3 commits into from
Feb 9, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 21 additions & 1 deletion ctx.go
Original file line number Diff line number Diff line change
Expand Up @@ -1126,6 +1126,27 @@ func (c *Ctx) QueryInt(key string, defaultValue ...int) int {
return value
}

// QueryBool returns bool value of key string parameter in the url.
// Default to empty or invalid key is true.
//
// Get /?name=alex&want_pizza=false&id=
// QueryBool("want_pizza") == false
// QueryBool("want_pizza", true) == false
// QueryBool("alex") == true
// QueryBool("alex", false) == false
// QueryBool("id") == true
// QueryBool("id", false) == false
func (c *Ctx) QueryBool(key string, defaultValue ...bool) bool {
value, err := strconv.ParseBool(c.app.getString(c.fasthttp.QueryArgs().Peek(key)))
if err != nil {
if len(defaultValue) > 0 {
return defaultValue[0]
}
return true
}
return value
}

// QueryFloat returns float64 value of key string parameter in the url.
// Default to empty or invalid key is 0.
//
Expand All @@ -1144,7 +1165,6 @@ func (c *Ctx) QueryFloat(key string, defaultValue ...float64) float64 {
}
return 0
}

return value
}

Expand Down
15 changes: 15 additions & 0 deletions ctx_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2149,6 +2149,21 @@ func Test_Ctx_QueryInt(t *testing.T) {
utils.AssertEqual(t, 2, c.QueryInt("id", 2))
}

func Test_Ctx_QueryBool(t *testing.T) {
t.Parallel()
app := New()
c := app.AcquireCtx(&fasthttp.RequestCtx{})
defer app.ReleaseCtx(c)
c.Request().URI().SetQueryString("name=alex&want_pizza=false&id=")

utils.AssertEqual(t, false, c.QueryBool("want_pizza"))
utils.AssertEqual(t, false, c.QueryBool("want_pizza", true))
utils.AssertEqual(t, true, c.QueryBool("name"))
utils.AssertEqual(t, false, c.QueryBool("name", false))
utils.AssertEqual(t, true, c.QueryBool("id"))
utils.AssertEqual(t, false, c.QueryBool("id", false))
}

func Test_Ctx_QueryFloat(t *testing.T) {
t.Parallel()
app := New()
Expand Down