Go 1.22: stdlib routing with method matching — goodbye gorilla/mux

Posted by Tara Rani · 2024-03-16

Go 1.22 adds method-based routing to the standard library. No more gorilla/mux or chi for basic REST APIs. The pattern syntax covers 90% of use cases. https://github.com/golang/go/releases/tag/go1.22.0

// Go 1.22 stdlib routing — no external router needed
package main

import "net/http"

func main() {
	mux := http.NewServeMux()
	mux.HandleFunc("GET /api/users/{id}", getUser)
	mux.HandleFunc("POST /api/users", createUser)
	mux.HandleFunc("DELETE /api/users/{id}", deleteUser)
	mux.HandleFunc("GET /api/posts/{slug...}", getPost)
	http.ListenAndServe(":8080", mux)
}

func getUser(w http.ResponseWriter, r *http.Request) {
	id := r.PathValue("id")
}

Explore GitVibes