liveBook · Manning

Route parameter

As explained in Learn Go with Pocket-Sized Projects

A path parameter is a required value encoded as part of a URL path and used to identify or select a resource.

Suppose a service can create games, but now needs to return the status of one game. Give each game a path such as `/games/{id}`: the value in the URL identifies the resource the caller wants. The braces mark a variable part of the route, not characters the caller types literally. section 8.2.2

In a Go HTTP handler:

  • Register a method and route together, for example `http.MethodGet + " /games/{id}"`. section 8.2.2
  • Read the captured value with `request.PathValue("id")`. Keep the name consistent with the wildcard in the route. section 8.2.2 section 8.7
  • Check for an empty value before using it. The game-status handler returns an HTTP error when its ID is missing. section 8.2.2

Test the handler directly

A handler test creates a GET request, calls `req.SetPathValue("id", "123456")`, and passes the request to the handler with an `httptest` recorder. It then checks the response status and JSON game ID. Setting the path value explicitly matters here because the test calls the handler rather than sending the request through the router. section 8.2.2

A route can have more than one wildcard, as in `/users/{user_id}/games/{game_id}`. Choose path parameters to select a particular resource; use query parameters when filtering resources, where a request might return zero, one, or many results. section 8.7 section 8.2.2

The same pattern works for a browser link to `/tick/{habitID}`. A handler reads `r.PathValue("habitID")`; its test sets that value explicitly. Ticking changes state, though, so a GET link is only an interim choice: use POST for the action and a redirect afterward to avoid repeating it on refresh. section 11.3.1

How Learn Go with Pocket-Sized Projects covers it

How deep it goes
Works through route registration, value extraction, missing-value checks, and handler tests without examining router internals.
Examples
Uses `/games/{id}`, a multi-wildcard user-and-game route, and a `/tick/{habitID}` link with handler tests.
What it assumes
Assumes familiarity with Go HTTP requests and handlers while introducing wildcard routes and PathValue through examples.
What you can do after
Apply it via Go net/http to register resource-specific routes, read their identifiers, and test handlers.
How it connects
Contrasts path parameters with query parameters and connects them to REST APIs, HTTP handlers, status codes, and redirects.

Also explained in

Compare how 6 books explain route parameter →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Go with Pocket-Sized Projects. The section links point to the parts of the book it draws on.