Skip to content

Commit

Permalink
🔥 Feature: add queryBool parser (#2329)
Browse files Browse the repository at this point in the history
* 🔥 Feature: add queryBool parser

* 🩹 pass linter
  • Loading branch information
dozheiny authored Feb 9, 2023
1 parent 54439a5 commit c3b151a
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 1 deletion.
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

0 comments on commit c3b151a

Please sign in to comment.