Skip to content

Commit

Permalink
🔥 Feature: add queryFloat parser (#2328)
Browse files Browse the repository at this point in the history
  • Loading branch information
dozheiny authored Feb 9, 2023
1 parent 61a3336 commit 54439a5
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
22 changes: 22 additions & 0 deletions ctx.go
Original file line number Diff line number Diff line change
Expand Up @@ -1126,6 +1126,28 @@ func (c *Ctx) QueryInt(key string, defaultValue ...int) int {
return value
}

// QueryFloat returns float64 value of key string parameter in the url.
// Default to empty or invalid key is 0.
//
// GET /?name=alex&amount=32.23&id=
// QueryFloat("amount") = 32.23
// QueryFloat("amount", 3) = 32.23
// QueryFloat("name", 1) = 1
// QueryFloat("name") = 0
// QueryFloat("id", 3) = 3
func (c *Ctx) QueryFloat(key string, defaultValue ...float64) float64 {
// use strconv.ParseFloat to convert the param to a float or return zero and an error.
value, err := strconv.ParseFloat(c.app.getString(c.fasthttp.QueryArgs().Peek(key)), 64)
if err != nil {
if len(defaultValue) > 0 {
return defaultValue[0]
}
return 0
}

return value
}

// QueryParser binds the query string to a struct.
func (c *Ctx) QueryParser(out interface{}) error {
data := make(map[string][]string)
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_QueryFloat(t *testing.T) {
t.Parallel()
app := New()
c := app.AcquireCtx(&fasthttp.RequestCtx{})
defer app.ReleaseCtx(c)
c.Request().URI().SetQueryString("name=alex&amount=32.23&id=")

utils.AssertEqual(t, 32.23, c.QueryFloat("amount"))
utils.AssertEqual(t, 32.23, c.QueryFloat("amount", 3.123))
utils.AssertEqual(t, 87.123, c.QueryFloat("name", 87.123))
utils.AssertEqual(t, float64(0), c.QueryFloat("name"))
utils.AssertEqual(t, 12.87, c.QueryFloat("id", 12.87))
utils.AssertEqual(t, float64(0), c.QueryFloat("id"))
}

// go test -run Test_Ctx_Range
func Test_Ctx_Range(t *testing.T) {
t.Parallel()
Expand Down

0 comments on commit 54439a5

Please sign in to comment.