Skip to content

Commit 54439a5

Browse files
authored
🔥 Feature: add queryFloat parser (#2328)
1 parent 61a3336 commit 54439a5

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

ctx.go

+22
Original file line numberDiff line numberDiff line change
@@ -1126,6 +1126,28 @@ func (c *Ctx) QueryInt(key string, defaultValue ...int) int {
11261126
return value
11271127
}
11281128

1129+
// QueryFloat returns float64 value of key string parameter in the url.
1130+
// Default to empty or invalid key is 0.
1131+
//
1132+
// GET /?name=alex&amount=32.23&id=
1133+
// QueryFloat("amount") = 32.23
1134+
// QueryFloat("amount", 3) = 32.23
1135+
// QueryFloat("name", 1) = 1
1136+
// QueryFloat("name") = 0
1137+
// QueryFloat("id", 3) = 3
1138+
func (c *Ctx) QueryFloat(key string, defaultValue ...float64) float64 {
1139+
// use strconv.ParseFloat to convert the param to a float or return zero and an error.
1140+
value, err := strconv.ParseFloat(c.app.getString(c.fasthttp.QueryArgs().Peek(key)), 64)
1141+
if err != nil {
1142+
if len(defaultValue) > 0 {
1143+
return defaultValue[0]
1144+
}
1145+
return 0
1146+
}
1147+
1148+
return value
1149+
}
1150+
11291151
// QueryParser binds the query string to a struct.
11301152
func (c *Ctx) QueryParser(out interface{}) error {
11311153
data := make(map[string][]string)

ctx_test.go

+15
Original file line numberDiff line numberDiff line change
@@ -2149,6 +2149,21 @@ func Test_Ctx_QueryInt(t *testing.T) {
21492149
utils.AssertEqual(t, 2, c.QueryInt("id", 2))
21502150
}
21512151

2152+
func Test_Ctx_QueryFloat(t *testing.T) {
2153+
t.Parallel()
2154+
app := New()
2155+
c := app.AcquireCtx(&fasthttp.RequestCtx{})
2156+
defer app.ReleaseCtx(c)
2157+
c.Request().URI().SetQueryString("name=alex&amount=32.23&id=")
2158+
2159+
utils.AssertEqual(t, 32.23, c.QueryFloat("amount"))
2160+
utils.AssertEqual(t, 32.23, c.QueryFloat("amount", 3.123))
2161+
utils.AssertEqual(t, 87.123, c.QueryFloat("name", 87.123))
2162+
utils.AssertEqual(t, float64(0), c.QueryFloat("name"))
2163+
utils.AssertEqual(t, 12.87, c.QueryFloat("id", 12.87))
2164+
utils.AssertEqual(t, float64(0), c.QueryFloat("id"))
2165+
}
2166+
21522167
// go test -run Test_Ctx_Range
21532168
func Test_Ctx_Range(t *testing.T) {
21542169
t.Parallel()

0 commit comments

Comments
 (0)