mirror of https://github.com/gofiber/fiber.git
🔥 Feature: add queryFloat parser (#2328)
parent
61a3336119
commit
54439a5bde
22
ctx.go
22
ctx.go
|
@ -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)
|
||||
|
|
15
ctx_test.go
15
ctx_test.go
|
@ -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()
|
||||
|
|
Loading…
Reference in New Issue