Skip to content

Commit

Permalink
🔥 write integer Query Parser. (#2306)
Browse files Browse the repository at this point in the history
* Feature: write integer Query Parser.

* request changes on #2306 (comment)

* ref(test): separate test cases for QueryInt
  • Loading branch information
dozheiny committed Jan 23, 2023
1 parent c5691c7 commit a0004cf
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 1 deletion.
22 changes: 22 additions & 0 deletions ctx.go
Original file line number Diff line number Diff line change
Expand Up @@ -1086,6 +1086,28 @@ func (c *Ctx) Query(key string, defaultValue ...string) string {
return defaultString(c.app.getString(c.fasthttp.QueryArgs().Peek(key)), defaultValue)
}

// QueryInt returns integer value of key string parameter in the url.
// Default to empty or invalid key is 0.
//
// GET /?name=alex&wanna_cake=2&id=
// QueryInt("wanna_cake", 1) == 2
// QueryInt("name", 1) == 1
// QueryInt("id", 1) == 1
// QueryInt("id") == 0
func (c *Ctx) QueryInt(key string, defaultValue ...int) int {
// Use Atoi to convert the param to an int or return zero and an error
value, err := strconv.Atoi(c.app.getString(c.fasthttp.QueryArgs().Peek(key)))
if err != nil {
if len(defaultValue) > 0 {
return defaultValue[0]
} else {
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
17 changes: 16 additions & 1 deletion ctx_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2115,12 +2115,27 @@ func Test_Ctx_Query(t *testing.T) {
app := New()
c := app.AcquireCtx(&fasthttp.RequestCtx{})
defer app.ReleaseCtx(c)
c.Request().URI().SetQueryString("search=john&age=20")
c.Request().URI().SetQueryString("search=john&age=20&id=")
utils.AssertEqual(t, "john", c.Query("search"))
utils.AssertEqual(t, "20", c.Query("age"))
utils.AssertEqual(t, "default", c.Query("unknown", "default"))
}

func Test_Ctx_QueryInt(t *testing.T) {
t.Parallel()
app := New()
c := app.AcquireCtx(&fasthttp.RequestCtx{})
defer app.ReleaseCtx(c)
c.Request().URI().SetQueryString("search=john&age=20&id=")

utils.AssertEqual(t, 0, c.QueryInt("foo"))
utils.AssertEqual(t, 20, c.QueryInt("age", 12))
utils.AssertEqual(t, 0, c.QueryInt("search"))
utils.AssertEqual(t, 1, c.QueryInt("search", 1))
utils.AssertEqual(t, 0, c.QueryInt("id"))
utils.AssertEqual(t, 2, c.QueryInt("id", 2))
}

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

0 comments on commit a0004cf

Please sign in to comment.