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.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
