liveBook · Manning

Parameter

As explained in Learn Go with Pocket-Sized Projects

A query parameter is an optional key-value component of a URL that supplies filtering or other request options to an API.

A query parameter is an optional key-value pair in a URL that supplies a request option or filter. It follows the path after `?`; multiple pairs are separated by `&`, as in `{path}?key1=value1&key2=value2`. A filter can match zero, one, or many resources. section 8.2.2 section 8.6.5

Choose a game language

In `http://localhost:8080/game?lang=en`, `lang` is the key and `en` is its value. A game-creation handler can read that choice from the request URL. section 8.6.5

Listing 8.43 newgame/handler.go: Reading the query parameter in handler
// Handler returns the handler for the game creation endpoint.
func Handler(db gameAdder) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) { #1
        lang := r.URL.Query().Get(api.Lang) #2
        if len(lang) > 0 {
            // TODO create a game in the chosen language
            fmt.Println(lang) #3
        }

The Go handler retrieves the value with `r.URL.Query().Get(api.Lang)` and checks whether it is nonempty. Creating a game in the chosen language remains a TODO. section 8.6.5

`URL.Query()` returns `url.Values`, which maps string keys to lists of values; its keys are case-sensitive. `Get` retrieves a value by key. A named constant such as `Lang = "lang"` keeps the parameter key alongside other API constants. section 8.6.5

Unlike a query parameter, a path parameter identifies a resource in the route, such as `/games/{gameID}`. Other request inputs include bodies and headers. section 8.2.2

Navigate by week

A habit tracker can accept a `week` query parameter for previous and next navigation, defaulting to `time.Now()` when it is absent. Test the parameter and consider direct requests for future weeks, not just whether the Next button is hidden. section 11.5.1

How Learn Go with Pocket-Sized Projects covers it

How deep it goes
Explains query syntax and Go retrieval through a handler, leaving language-specific game creation as a TODO.
Examples
Shows `lang=en` for game creation and proposes a `week` parameter for habit-tracker navigation.
What you can do after
Apply it via Go's `net/http` request URL to retrieve optional query values and plan defaults and request tests.
How it connects
Distinguishes query parameters from path parameters and relates them to HTTP requests, REST APIs, and URL query strings.

Also explained in

Compare how 32 books explain 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.