Skip to content

Commit

Permalink
v3: Add QueryParser for get query using generic (#2776)
Browse files Browse the repository at this point in the history
* Add QueryParser method and tests

Introduced a new method, QueryParser, to parse query parameters from a given context into specified types: integer, boolean, float, and string. The method provides default values for empty or invalid keys. Corresponding tests for each type have also been added to validate the functionality.

* Refactor QueryParser and add string support

Refactored the existing QueryParser method in the code to simplify its structure. Instead of reflecting on types, it now uses explicit type checking. In addition to the existing support for integers, booleans, and floats, the QueryParser method now also supports string parsing. Corresponding tests for the updated method and new feature were added as well.

* Update example call in method comment

Updated the method call example in the comment for the Query function in the ctx.go file. Previously, it was incorrectly demonstrating a call to "QueryParser("wanna_cake", 1)", but this has been updated to correctly represent the method it is commenting, resulting in "Query("wanna_cake", 1)".

* Refactor Query function in ctx.go

The update introduces better type assertion handling in the Query function. A switch statement is now employed to determine the type of the value as opposed to the previous if clauses. In addition, a validation step has been added to ensure the context passed into the function is of the correct type.

* Refactor type handling in Query function

The Query function in ctx.go has been refactored for better and clearer type handling. The code now uses a 'QueryType' interface, replacing explicit string, bool, float, and int declarations. This change also improves the error message when a type assertion fails, making it more descriptive about the specific failure.

* Add type assertion check in ctx.go

Updated the code in ctx.go to add a type assertion check for all case statements. The function now checks if the returned value is of the expected type, and if not, it throws a panic with a description of the failed type assertion.

* Refactor Query function to support more data types

The Query function has been expanded to support a broader range of data types. This includes support for extracting query parameters as different types of integers (both signed and unsigned), strings, floats, and booleans from the request's URI. The function now includes comprehensive parsing capabilities that allow for improved handling of different data types.

* Refactor Query function documentation

The documentation for the Query function has been updated to emphasize its versatility in handling various data types. The changes also clarify how the function operates and demonstrates the usage and benefits of providing a defaultValue. The different variations of QueryBool, QueryFloat, and QueryInt were removed, as they are now encompassed by the enhanced Query function.

* Add benchmark tests for Query function

Benchmark tests have been added to evaluate the performance of the Query function for different data types. These tests will help in assessing the efficiency of the function when processing various queries. The addition of these benchmarks will aid in future optimizations and enhancements of the function.

* Update generic Query function signature

The signature of the generic Query function has been updated to accept different types of data as arguments. The change improves flexibility of the function by allowing it to handle different data types, effectively making it a versatile tool in processing various queries.

* Modify `ctx.Query()` calls in documentation

`ctx.Query()` calls in the ctx.md documentation file were updated to remove the `ctx.` prefix. This is consistent with the typical use cases and makes the code examples more clear and easy to understand.

* Refactored assertValueType function and improved query parameter documentation

Updated the assertValueType function to utilize the utils.UnsafeBytes method for byte conversion. Enhanced the documentation for query parameter types to offer clearer, more comprehensive explanations and examples, including QueryTypeInteger, QueryTypeFloat, and subcategories.

* Update Query method calls to use new fiber.Query syntax

In this commit, the conventional `c.Query()` calls across multiple middleware and document files are updated to use the new `fiber.Query` syntax. The changes align with the updated function signatures in Fiber library that provides type-specific querying. These enhancements contribute to the project's overall robustness and consistency.

* Add Query method to get query string parameters

* Replace 'utils.UnsafeBytes' with 'ctx.app.getBytes'

In the query method, the utils.UnsafeBytes function was replaced with the ctx.app.getBytes method. This change enhances the extraction of query string parameters by making it safer and more context-specific.

* Refactor parsing functions in query handlers

The parsing functions in query handlers have been refactored to simplify the process. Parsing code has been extracted into dedicated functions like 'parseIntWithDefault' and 'parseFloatWithDefault', and they now reside in a new utils file. This modularization improves readability and maintainability of the code. Additionally, documentation is updated to reflect the changes.

* Refactor parsing functions in ctx.go

The parsing functions have been restructured to enhance readability and reduce repetition in the ctx.go file. This was achieved by creating generalised parsing functions that handle defaults and ensure the correct value type is returned. As a result, various single-use parsing functions in the utils.go file have been removed.

* Refactor code to centralize parsing functions
  • Loading branch information
ryanbekhen authored Jan 19, 2024
1 parent 603fbde commit 9a56a1b
Show file tree
Hide file tree
Showing 13 changed files with 597 additions and 203 deletions.
135 changes: 83 additions & 52 deletions ctx.go
Original file line number Diff line number Diff line change
Expand Up @@ -1005,7 +1005,7 @@ func (c *DefaultCtx) Protocol() string {
// Returned value is only valid within the handler. Do not store any references.
// Make copies or use the Immutable setting to use the value outside the Handler.
func (c *DefaultCtx) Query(key string, defaultValue ...string) string {
return defaultString(c.app.getString(c.fasthttp.QueryArgs().Peek(key)), defaultValue)
return Query[string](c, key, defaultValue...)
}

// Queries returns a map of query parameters and their values.
Expand Down Expand Up @@ -1037,67 +1037,98 @@ func (c *DefaultCtx) Queries() map[string]string {
return m
}

// QueryInt returns integer value of key string parameter in the url.
// Default to empty or invalid key is 0.
// Query Retrieves the value of a query parameter from the request's URI.
// The function is generic and can handle query parameter values of different types.
// It takes the following parameters:
// - c: The context object representing the current request.
// - key: The name of the query parameter.
// - defaultValue: (Optional) The default value to return in case the query parameter is not found or cannot be parsed.
// The function performs the following steps:
// 1. Type-asserts the context object to *DefaultCtx.
// 2. Retrieves the raw query parameter value from the request's URI.
// 3. Parses the raw value into the appropriate type based on the generic type parameter V.
// If parsing fails, the function checks if a default value is provided. If so, it returns the default value.
// 4. Returns the parsed value.
//
// 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 *DefaultCtx) 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 the generic type cannot be matched to a supported type, the function returns the default value (if provided) or the zero value of type V.
//
// Example usage:
//
// GET /?search=john&age=8
// name := Query[string](c, "search") // Returns "john"
// age := Query[int](c, "age") // Returns 8
// unknown := Query[string](c, "unknown", "default") // Returns "default" since the query parameter "unknown" is not found
func Query[V QueryType](c Ctx, key string, defaultValue ...V) V {
ctx, ok := c.(*DefaultCtx)
if !ok {
panic(fmt.Errorf("failed to type-assert to *DefaultCtx"))
}
var v V
q := ctx.app.getString(ctx.fasthttp.QueryArgs().Peek(key))

switch any(v).(type) {
case int:
return queryParseInt[V](q, 32, func(i int64) V { return assertValueType[V, int](int(i)) }, defaultValue...)
case int8:
return queryParseInt[V](q, 8, func(i int64) V { return assertValueType[V, int8](int8(i)) }, defaultValue...)
case int16:
return queryParseInt[V](q, 16, func(i int64) V { return assertValueType[V, int16](int16(i)) }, defaultValue...)
case int32:
return queryParseInt[V](q, 32, func(i int64) V { return assertValueType[V, int32](int32(i)) }, defaultValue...)
case int64:
return queryParseInt[V](q, 64, func(i int64) V { return assertValueType[V, int64](i) }, defaultValue...)
case uint:
return queryParseUint[V](q, 32, func(i uint64) V { return assertValueType[V, uint](uint(i)) }, defaultValue...)
case uint8:
return queryParseUint[V](q, 8, func(i uint64) V { return assertValueType[V, uint8](uint8(i)) }, defaultValue...)
case uint16:
return queryParseUint[V](q, 16, func(i uint64) V { return assertValueType[V, uint16](uint16(i)) }, defaultValue...)
case uint32:
return queryParseUint[V](q, 32, func(i uint64) V { return assertValueType[V, uint32](uint32(i)) }, defaultValue...)
case uint64:
return queryParseUint[V](q, 64, func(i uint64) V { return assertValueType[V, uint64](i) }, defaultValue...)
case float32:
return queryParseFloat[V](q, 32, func(i float64) V { return assertValueType[V, float32](float32(i)) }, defaultValue...)
case float64:
return queryParseFloat[V](q, 64, func(i float64) V { return assertValueType[V, float64](i) }, defaultValue...)
case bool:
return queryParseBool[V](q, func(b bool) V { return assertValueType[V, bool](b) }, defaultValue...)
case string:
if q == "" && len(defaultValue) > 0 {
return defaultValue[0]
}
return assertValueType[V, string](q)
case []byte:
if q == "" && len(defaultValue) > 0 {
return defaultValue[0]
}
return assertValueType[V, []byte](ctx.app.getBytes(q))
default:
if len(defaultValue) > 0 {
return defaultValue[0]
}
return 0
return v
}
}

return value
type QueryType interface {
QueryTypeInteger | QueryTypeFloat | bool | string | []byte
}

// QueryBool returns bool value of key string parameter in the url.
// Default to empty or invalid key is true.
//
// Get /?name=alex&want_pizza=false&id=
// QueryBool("want_pizza") == false
// QueryBool("want_pizza", true) == false
// QueryBool("name") == false
// QueryBool("name", true) == true
// QueryBool("id") == false
// QueryBool("id", true) == true
func (c *DefaultCtx) QueryBool(key string, defaultValue ...bool) bool {
value, err := strconv.ParseBool(c.app.getString(c.fasthttp.QueryArgs().Peek(key)))
if err != nil {
if len(defaultValue) > 0 {
return defaultValue[0]
}
return false
}
return value
type QueryTypeInteger interface {
QueryTypeIntegerSigned | QueryTypeIntegerUnsigned
}

// 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 *DefaultCtx) 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
type QueryTypeIntegerSigned interface {
int | int8 | int16 | int32 | int64
}

type QueryTypeIntegerUnsigned interface {
uint | uint8 | uint16 | uint32 | uint64
}

type QueryTypeFloat interface {
float32 | float64
}

// Range returns a struct containing the type and a slice of ranges.
Expand Down
45 changes: 6 additions & 39 deletions ctx_interface.go
Original file line number Diff line number Diff line change
Expand Up @@ -232,13 +232,6 @@ type Ctx interface {
// Protocol returns the HTTP protocol of request: HTTP/1.1 and HTTP/2.
Protocol() string

// Query returns the query string parameter in the url.
// Defaults to empty string "" if the query doesn't exist.
// If a default value is given, it will return that value if the query doesn't exist.
// Returned value is only valid within the handler. Do not store any references.
// Make copies or use the Immutable setting to use the value outside the Handler.
Query(key string, defaultValue ...string) string

// Queries returns a map of query parameters and their values.
//
// GET /?name=alex&wanna_cake=2&id=
Expand All @@ -262,38 +255,12 @@ type Ctx interface {
// Queries()["filters[status]"] == "pending"
Queries() map[string]string

// 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
QueryInt(key string, defaultValue ...int) int

// QueryBool returns bool value of key string parameter in the url.
// Default to empty or invalid key is true.
//
// Get /?name=alex&want_pizza=false&id=
// QueryBool("want_pizza") == false
// QueryBool("want_pizza", true) == false
// QueryBool("name") == false
// QueryBool("name", true) == true
// QueryBool("id") == false
// QueryBool("id", true) == true
QueryBool(key string, defaultValue ...bool) bool

// 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
QueryFloat(key string, defaultValue ...float64) float64
// Query returns the query string parameter in the url.
// Defaults to empty string "" if the query doesn't exist.
// If a default value is given, it will return that value if the query doesn't exist.
// Returned value is only valid within the handler. Do not store any references.
// Make copies or use the Immutable setting to use the value outside the Handler.
Query(key string, defaultValue ...string) string

// Range returns a struct containing the type and a slice of ranges.
Range(size int) (rangeData Range, err error)
Expand Down
Loading

0 comments on commit 9a56a1b

Please sign in to comment.