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

🔥 write integer Query Parser. #2306

Merged
merged 3 commits into from
Jan 23, 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 @@ -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