Skip to content

Instantly share code, notes, and snippets.

@Integralist
Created October 9, 2025 11:49
Show Gist options
  • Save Integralist/c857191822d2af1df915af0403fc2fcf to your computer and use it in GitHub Desktop.
Save Integralist/c857191822d2af1df915af0403fc2fcf to your computer and use it in GitHub Desktop.
Go URL filter query parsing
package main
import (
"fmt"
"net/http"
"net/url"
)
func main() {
// Simulate a URL with filter parameters
rawURL := "http://example.com/whatever?filter[certificate_authority]=certainly&filter[state]=pending&limit=10"
// Parse the URL
parsedURL, err := url.Parse(rawURL)
if err != nil {
fmt.Println("Error parsing URL:", err)
return
}
// Get query parameters
query := parsedURL.Query()
// Direct access with bracket notation
certAuthority := query.Get("filter[certificate_authority]")
state := query.Get("filter[state]")
limit := query.Get("limit")
// Display results
fmt.Println("=== Parsed Query Parameters ===")
fmt.Printf("Certificate Authority: %q\n", certAuthority)
fmt.Printf("State: %q\n", state)
fmt.Printf("Limit: %q\n", limit)
// Show all query parameters
fmt.Println("\n=== All Query Parameters ===")
for key, values := range query {
fmt.Printf("%s = %v\n", key, values)
}
// Example: Build a handler function
fmt.Println("\n=== Using in HTTP Handler ===")
simulateHandler(parsedURL.Query())
}
// Simulate an HTTP handler
func simulateHandler(query url.Values) {
certAuthority := query.Get("filter[certificate_authority]")
state := query.Get("filter[state]")
if certAuthority == "" && state == "" {
fmt.Println("No filters provided")
return
}
fmt.Println("Processing filters:")
if certAuthority != "" {
fmt.Printf(" - Certificate Authority: %s\n", certAuthority)
}
if state != "" {
fmt.Printf(" - State: %s\n", state)
}
}
// Bonus: Example with actual http.Request
func exampleHTTPHandler(w http.ResponseWriter, r *http.Request) {
query := r.URL.Query()
certAuthority := query.Get("filter[certificate_authority]")
state := query.Get("filter[state]")
fmt.Fprintf(w, "Certificate Authority: %s\n", certAuthority)
fmt.Fprintf(w, "State: %s\n", state)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment