Golang / GoLang Production Patterns and Web Standards Interview Questions
How has http.ServeMux evolved in Go 1.22 and what routing patterns does it support?
Go 1.22 significantly upgraded http.ServeMux with method-based routing, path parameters, and wildcard matching — reducing the need for third-party routers in many applications.
mux := http.NewServeMux() // Go 1.22+ enhanced routing patterns: // Method + exact path mux.HandleFunc("GET /health", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) w.Write([]byte(`{"status":"ok"}`)) }) // Method + path with named parameter {id} mux.HandleFunc("GET /users/{id}", func(w http.ResponseWriter, r *http.Request) { id := r.PathValue("id") // extract path variable fmt.Fprintf(w, "user %s", id) }) // Method + path with wildcard {path...} (matches remainder) mux.HandleFunc("GET /files/{path...}", func(w http.ResponseWriter, r *http.Request) { path := r.PathValue("path") http.ServeFile(w, r, filepath.Join("/static", path)) }) // POST with body mux.HandleFunc("POST /users", createUserHandler) // DELETE mux.HandleFunc("DELETE /users/{id}", deleteUserHandler) // Host-based routing mux.HandleFunc("api.example.com/GET /v1/", apiV1Handler) // Trailing slash subtree pattern (matches /api/ and all sub-paths) mux.HandleFunc("/api/", apiHandler) // Pre-1.22 pattern: no method prefix, manual method check // mux.HandleFunc("/users", func(w http.ResponseWriter, r *http.Request) { // switch r.Method { // case http.MethodGet: listUsers(w, r) // case http.MethodPost: createUser(w, r) // default: http.Error(w, "method not allowed", 405) // } // })
Go 1.22 routing precedence: more specific patterns win over less specific ones. A pattern with a method is more specific than one without. An exact path is more specific than a wildcard. If two patterns conflict (same specificity, overlapping matches), the registration panics at startup — catching routing mistakes at boot time rather than silently returning wrong responses.
More Related questions...