typestar

Routing with the standard mux in Go

Go 1.22 taught ServeMux methods and path variables.

func newMux() *http.ServeMux {
    mux := http.NewServeMux()

    mux.HandleFunc("GET /healthz", func(w http.ResponseWriter,
        r *http.Request) {
        fmt.Fprint(w, "ok")
    })

    mux.HandleFunc("GET /tours/{slug}", func(w http.ResponseWriter,
        r *http.Request) {
        slug := r.PathValue("slug")
        w.Header().Set("Content-Type", "application/json")
        json.NewEncoder(w).Encode(map[string]string{"slug": slug})
    })

    mux.HandleFunc("POST /results", func(w http.ResponseWriter,
        r *http.Request) {
        defer r.Body.Close()
        w.WriteHeader(http.StatusCreated)
    })

    return mux
}

How it works

  1. The pattern may start with a method: GET /tours/{slug}.
  2. r.PathValue reads a variable out of the path.
  3. No third-party router needed for this shape of API.

Keywords and builtins used here

The run, in numbers

Lines
23
Characters to type
535
Tokens
149
Three-star pace
110 tpm

At the three-star pace of 110 tokens a minute, this run takes about 81 seconds.

Type this snippet

Step 1 of 5 in HTTP, step 16 of 26 in Standard library & project layout.

← Previous Next →