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 queryFloat parser #2328

Merged
merged 1 commit 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: 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)
li-jin-gou marked this conversation as resolved.
Show resolved Hide resolved
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