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
