liveBook · Manning

Wildcard

As explained in Go in Practice, Second Edition

A wildcard is a route-pattern element that matches a variable portion of a URL path.

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

How Go in Practice, Second Edition covers it

How deep it goes
Works through ServeMux patterns and PathValue retrieval, then points to regular expressions for more complex matching.
Examples
Shows `/goodbye/` alongside `GET /goodbye/{name}` and contrasts PathValue with manual URL-path splitting.
What it assumes
Assumes basic Go HTTP handlers while showing how to register patterns and retrieve path values.
What you can do after
Apply it via Go’s ServeMux to route a variable path and read its value in a handler.
How it connects
Connects named URL variables to HTTP methods, route precedence, handlers, and RESTful routing.

Also explained in

Compare how 8 books explain wildcard →

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.