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

