Skip to main content

One Handler per Route

Routing decides which handler answers which request. Go's built-in router is http.ServeMux: you register patterns, it dispatches.

Patterns can include the method and path parameters in braces: "GET /users/{id}" matches GET /users/7 and hands you the 7 through r.PathValue("id"). Frameworks add conveniences on top, but this covers the everyday needs out of the box.


Routes and Path Values

Two routes: the list at /users and one user at /users/{id}. The braces part is the path parameter — the piece of the URL that is data.

A route with a path parameter

The same mux sends /users to one handler and /users/7 to another, and r.PathValue("id") extracts the 7 without any string cutting.

Prompt
Write a Go program with an http.ServeMux with two routes: GET /users returning a list line and GET /users/{id} using r.PathValue to answer about one user. Serve it with httptest, request both routes and print the responses.
Output: Go program and captured output

Query Parameters

The part after ? holds query parameters — options for the request, like a search text or a limit: /search?q=go&limit=2. They come from r.URL.Query(), always as strings, with Get returning "" for missing ones.

The rule of thumb: the path says which resource, the query says how — filters, sorting, paging.

Reading the query string

The handler reads q and limit from the query. The second request skips limit, so the handler falls back to a default — missing parameters are normal, plan for them.

Prompt
Write a Go program with a /search handler that reads the q and limit query parameters with r.URL.Query, using a default limit when it is missing. Serve with httptest, request it once with both parameters and once with only q, printing the responses.
Output: Go program and captured output