How to Handle Query Parameters in Go: Simple Guide
In Go, you handle query parameters by using the
Request.URL.Query() method which returns a map of query keys to their values. You can access parameters by their key and convert them to the needed type. Always check if the parameter exists to avoid errors.Why This Happens
Beginners often try to read query parameters directly from the URL string or forget to parse them properly, leading to errors or empty values. The root cause is misunderstanding how Go's net/http package provides query parameters.
go
package main import ( "fmt" "net/http" ) func handler(w http.ResponseWriter, r *http.Request) { // Incorrect: Trying to read query parameters directly from URL string query := r.URL.String() fmt.Fprintf(w, "Query string: %s", query) } func main() { http.HandleFunc("/", handler) http.ListenAndServe(":8080", nil) }
Output
Query string: /?name=John&age=30
The Fix
Use r.URL.Query() to get a map of query parameters. Then access parameters by key and handle missing keys safely. Convert string values to needed types if necessary.
go
package main import ( "fmt" "net/http" "strconv" ) func handler(w http.ResponseWriter, r *http.Request) { // Parse query parameters params := r.URL.Query() // Get 'name' parameter name := params.Get("name") if name == "" { name = "Guest" } // Get 'age' parameter and convert to int ageStr := params.Get("age") age, err := strconv.Atoi(ageStr) if err != nil { age = 0 // default age if missing or invalid } fmt.Fprintf(w, "Hello %s, age %d", name, age) } func main() { http.HandleFunc("/", handler) http.ListenAndServe(":8080", nil) }
Output
Hello John, age 30
Prevention
Always use r.URL.Query() to access query parameters instead of parsing the URL string manually. Check if parameters exist before using them and handle conversion errors gracefully. Use default values when parameters are missing. Consider writing helper functions to simplify repeated parsing.
Related Errors
Common mistakes include:
- Using
r.FormValue()without callingr.ParseForm()first, which can cause empty values. - Ignoring errors when converting query parameters to numbers, leading to runtime panics.
- Assuming parameters always exist, causing unexpected empty strings.
Key Takeaways
Use r.URL.Query() to safely access query parameters in Go.
Always check if a query parameter exists before using it.
Convert query parameter strings to the needed type with error handling.
Provide default values for missing or invalid parameters.
Avoid parsing the raw URL string manually for query parameters.