Parse and validate path and query parameters
Parse and validate path and query parameters
Path parameters identify a resource; query parameters modify a request, for example pagination. Both are untrusted strings. Convert to the required type, check bounds and decide how to handle missing and repeated values. URL.Query silently discards malformed pairs; url.ParseQuery returns an error that a strict API can reject.
package main
import ( "fmt" "net/http" "net/http/httptest" "strconv" "strings")
func probe(h http.Handler, method, path, body string) *httptest.ResponseRecorder { w := httptest.NewRecorder() h.ServeHTTP(w, httptest.NewRequest(method, path, strings.NewReader(body))) return w}func main() { m := http.NewServeMux() m.HandleFunc("GET /items/{id}", func(w http.ResponseWriter, r *http.Request) { id, e := strconv.Atoi(r.PathValue("id")) if e != nil || id < 1 { http.Error(w, "invalid id", 400) return } fmt.Fprint(w, id) }) for _, p := range []string{"/items/7", "/items/0", "/items/abc"} { w := probe(m, "GET", p, "") fmt.Println(w.Code, strings.TrimSpace(w.Body.String())) }}Atoi returns an error for nonnumeric or overflowing input. The positive integer check adds a business constraint. http.Error writes a plain-text error and status; return immediately to avoid continuing the handler. A syntactically valid ID still requires existence and access checks.
Expected output:
200 7400 invalid id400 invalid idValidate one bounded page value
package main
import ( "errors" "fmt" "net/url" "strconv")
func page(raw string) (int, error) { q, e := url.ParseQuery(raw) if e != nil { return 0, e } v, ok := q["page"] if !ok { return 1, nil } if len(v) != 1 { return 0, errors.New("one page required") } n, e := strconv.Atoi(v[0]) if e != nil || n < 1 || n > 100 { return 0, errors.New("page must be 1..100") } return n, nil}func main() { for _, s := range []string{"", "page=3", "page=0", "page=2&page=3", "page=%ZZ"} { n, e := page(s) fmt.Println(n, e == nil) }}ParseQuery exposes malformed escapes. Checking the value slice rejects duplicate page keys rather than silently picking one. Missing page defaults to 1; present-but-empty is invalid. This parser deliberately allows unrelated keys. If your API forbids them, validate the full key set. Decoding is not escaping for HTML, SQL or other contexts.
Expected output:
1 true3 true0 false0 false0 falseTry it locally
Use page with page=100 and page=101. Print value and validity.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
HTTP servers 03: Parse and validate path and query parameters
Check the lesson objective before moving on.
Why use ParseQuery for strict validation?
What should a repeated scalar page key do in this contract?