File tree 2 files changed +37
-0
lines changed
2 files changed +37
-0
lines changed Original file line number Diff line number Diff line change @@ -1126,6 +1126,28 @@ func (c *Ctx) QueryInt(key string, defaultValue ...int) int {
1126
1126
return value
1127
1127
}
1128
1128
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
+
1129
1151
// QueryParser binds the query string to a struct.
1130
1152
func (c * Ctx ) QueryParser (out interface {}) error {
1131
1153
data := make (map [string ][]string )
Original file line number Diff line number Diff line change @@ -2149,6 +2149,21 @@ func Test_Ctx_QueryInt(t *testing.T) {
2149
2149
utils .AssertEqual (t , 2 , c .QueryInt ("id" , 2 ))
2150
2150
}
2151
2151
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
+
2152
2167
// go test -run Test_Ctx_Range
2153
2168
func Test_Ctx_Range (t * testing.T ) {
2154
2169
t .Parallel ()
You can’t perform that action at this time.
0 commit comments