liveBook · Manning

Path variable

As explained in Go in Practice, Second Edition

A path variable is a named value captured from a matched URL path and made available to the request handler.

A path variable captures a named part of a matched URL path for use by its handler. It is useful when an identifier belongs in the path—such as a comment ID—rather than in a query parameter. In Go 1.22 and later, register a pattern containing `{id}`, then read the captured string with `r.PathValue("id")`. section 8.2

Retrieve a comment by ID

Register `GET /comments/{id}` for a `getComment` handler. Inside the handler, `strconv.Atoi(r.PathValue("id"))` converts the captured value to an integer. The shown implementation returns 404 when the ID is zero or exceeds the comment count, and otherwise writes the selected comment. It handles a conversion error separately. section 8.2

Named patterns avoid splitting `r.URL.Path` inside each handler. A `GET /goodbye/{name}` route, for example, lets the handler read `req.PathValue("name")`; a separate `GET /goodbye/` route can handle requests without a name. Method-qualified patterns also distinguish requests by HTTP verb. When patterns overlap, routing depends on their specificity, so check which handler a new pattern will select. section 2.3.3 section 8.2

Listing 8.7 Extracting information from request path
func getComment(w http.ResponseWriter, r *http.Request) {
    commentID, err := strconv.Atoi(r.PathValue("id"))       #1
    if err != nil {                                    #2
        w.WriteHeader(http.StatusInternalServerError)
        return
    }
    if commentID == 0 || len(comments) < commentID {     #3
        w.WriteHeader(http.StatusNotFound)
        return
    }
    fmt.Fprintf(w, "Comment %d: %s", commentID, 
    comments[commentID-1].text)                                     #4
}

func main() {
    http.HandleFunc("GET /comments", getComments)
    http.HandleFunc("GET /comments/{id}", getComment)     #5
    http.HandleFunc("POST /comments", postComments)

    if err := http.ListenAndServe(":8000", nil); err != nil {
        panic(err)
    }
}

See the route registration, `PathValue` conversion, and response checks together in the comment handler. section 8.2

How Go in Practice, Second Edition covers it

How deep it goes
Works through route registration, value extraction, integer conversion, and response checks; does not develop advanced router internals.
Examples
Demonstrates `GET /comments/{id}` for comment lookup and `GET /goodbye/{name}` for a named greeting response.
What it assumes
Builds on HTTP handlers and URL paths while introducing PathValue as an alternative to manual extraction.
What you can do after
Apply it via Go’s ServeMux and Request.PathValue to read a named path segment in an HTTP handler.
How it connects
Connects HTTP method routing and ServeMux with query parameters, manual path parsing, and regular expressions as routing alternatives.

Also explained in

Compare how 2 books explain path variable →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Go in Practice, Second Edition. The section links point to the parts of the book it draws on.