Practical Examples
Real-World Query Parameter Scenarios
1. E-Commerce Product Filtering
func filterProducts(query url.Values) []Product {
var products []Product
category := query.Get("category")
minPrice := query.Get("min_price")
maxPrice := query.Get("max_price")
// Apply dynamic filtering
for _, product := range allProducts {
if category != "" && product.Category != category {
continue
}
if minPrice != "" {
min, _ := strconv.Atoi(minPrice)
if product.Price < min {
continue
}
}
products = append(products, product)
}
return products
}
graph LR
A[Query Parameters] --> B[Page Number]
A --> C[Results Per Page]
A --> D[Offset Calculation]
func getPaginatedResults(query url.Values) []Result {
page := query.Get("page")
limit := query.Get("limit")
pageNum, _ := strconv.Atoi(page)
resultsPerPage, _ := strconv.Atoi(limit)
if pageNum == 0 {
pageNum = 1
}
if resultsPerPage == 0 {
resultsPerPage = 10
}
offset := (pageNum - 1) * resultsPerPage
return fetchResults(offset, resultsPerPage)
}
Advanced Query Parsing Techniques
Handling Complex Queries
Scenario |
Query Example |
Parsing Technique |
Multi-Select |
?tags=golang&tags=web |
Multiple Value Handling |
Nested Params |
?filter[price]=50 |
Complex Parsing |
Boolean Flags |
?active=true |
Type Conversion |
Search and Filtering Example
type SearchFilter struct {
Keyword string
Category string
MinPrice float64
MaxPrice float64
SortBy string
}
func parseSearchQuery(query url.Values) SearchFilter {
filter := SearchFilter{
Keyword: query.Get("q"),
Category: query.Get("category"),
MinPrice: parseFloat(query.Get("min_price")),
MaxPrice: parseFloat(query.Get("max_price")),
SortBy: query.Get("sort"),
}
return filter
}
func parseFloat(value string) float64 {
price, err := strconv.ParseFloat(value, 64)
if err != nil {
return 0
}
return price
}
Security Considerations
Preventing Query Injection
func sanitizeQueryParams(query url.Values) url.Values {
sanitized := url.Values{}
for key, values := range query {
// Implement custom sanitization logic
sanitizedValues := []string{}
for _, value := range values {
cleanValue := sanitizeValue(value)
sanitizedValues = append(sanitizedValues, cleanValue)
}
sanitized[key] = sanitizedValues
}
return sanitized
}
- Cache parsed queries
- Use minimal type conversions
- Validate input early
- Implement efficient filtering
At LabEx, we emphasize writing clean, efficient query parsing code that balances functionality and performance.