How to Use the New ServeMux in Go 1.22+ (Method Matching, Wildcards)

Web
Use http.NewServeMux() with method-prefixed patterns and wildcard handlers to route HTTP requests in Go 1.22+.

Use http.NewServeMux() to create a router that supports method-specific handlers and wildcard patterns via HandleFunc or Handle.

package main

import (
	"net/http"
)

func main() {
	mux := http.NewServeMux()

	// Method matching: GET /api/items
	mux.HandleFunc("GET /api/items", func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("GET items"))
	})

	// Wildcard: /static/* matches /static/css/style.css
	mux.Handle("/static/", http.FileServer(http.Dir("./static")))

	http.ListenAndServe(":8080", mux)
}

In Go 1.22+, ServeMux automatically matches HTTP methods when using HandleFunc with a method-prefixed pattern (e.g., GET /path). Wildcards like /static/* are supported by passing a handler to Handle for the prefix.