When URL paths contain variable values, registering every exact path becomes impractical. Go’s route patterns can name a path value, letting a handler retrieve it without splitting the URL itself. section 2.3.3
Route a named path value
Register `GET /goodbye/{name}` with an `http.ServeMux`, then read the matched value in the handler with `req.PathValue("name")`. Register `GET /goodbye/` separately if requests without a name also need a response. The `GET` prefix restricts these patterns by HTTP method. section 2.3.3
This replaces a simpler approach that registers `/goodbye/` and splits `req.URL.Path` inside its handler. Go’s more specific route matching also helps distinguish overlapping paths. For patterns beyond these named variables, a regular-expression resolver is another option. section 2.3.3
Listing 2.16 Resolving URLs using path package
package main
import (
"fmt"
"net/http"
)
func main() {
mux := http.NewServeMux() #1
mux.HandleFunc("/hello", helloHandler) #2
mux.HandleFunc("GET /goodbye/", goodbyeHandler) #2
mux.HandleFunc("GET /goodbye/{name}", goodbyeHandler) #2
if err := http.ListenAndServe(":8084", mux); err != nil { #3
panic(err)
}
}
func helloHandler(res http.ResponseWriter, req *http.Request) {
query := req.URL.Query() #4
name := query.Get("name") #4
if name == "" {
name = "Inigo Montoya"
}
fmt.Fprint(res, "Hello, my name is ", name)
}
func goodbyeHandler(res http.ResponseWriter, req *http.Request) {
name := req.PathValue("name") #5
if name == "" { #5
name = "Inigo Montoya" #6
}
fmt.Fprint(res, "Goodbye ", name) #7
}
The working ServeMux listing shows both goodbye patterns and retrieval of the named value. section 2.3.3







