liveBook · Manning

PathValue

As explained in Learn Go with Pocket-Sized Projects

PathValue is an HTTP request method that returns the value associated with a named wildcard path parameter.

PathValue is an HTTP request method that retrieves the value associated with a named wildcard path parameter. A route such as /games/{id} exposes the captured value through request.PathValue("id"). section 8.7 section 8.2.2

Reading a game identifier

Register GET /games/{id}, then retrieve the identifier with request.PathValue(api.GameID). If the result is empty, return an HTTP error and stop the handler before writing anything else. section 8.2.2

Use PathValue when handling wildcard route parameters:

  • Name the wildcard consistently, preferably with a route constant such as GameID. section 8.2.2
  • Retrieve several parameters independently; /users/{user_id}/games/{game_id} can expose both user_id and game_id. section 8.7
  • Test handlers by creating a request and assigning the value with SetPathValue before invocation. section 8.2.2 section 11.3.1
Listing 8.14 handle.go: Status endpoint handler
func Handle(
    w http.ResponseWriter, request *http.Request) { #1
    id := request.PathValue(api.GameID) #2
    if id == "" { #3
        http.Error(writer, "missing the id of the game", 
            http.StatusBadRequest)
        return
    }
    log.Printf("retrieve status of game with id: %v", id)

    apiGame := api.GameResponse{
        ID: id,
    }
    // ... encode into JSON
}

Inspect a complete handler pattern that reads a path value, validates an empty result, and returns a JSON response. section 8.2.2

How Learn Go with Pocket-Sized Projects covers it

How deep it goes
Explains route naming, handler retrieval, empty-value errors, and request testing, but defers thorough identifier validation.
Examples
Uses game-status and habit-ticking endpoints, including /games/{id}, /tick/{habitID}, and httptest requests.
What it assumes
Assumes familiarity with HTTP routes and handler functions while demonstrating path-parameter retrieval and request setup.
What you can do after
Apply it via Go's net/http package to read route parameters and test handlers with assigned path values.
How it connects
Connects HTTP requests with wildcard path parameters, routes, handler functions, HTTP errors, and SetPathValue testing.

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.