Why is Go 1.22's enhanced routing not working for me?
A few weeks ago, I started looking at adding Go 1.22+'s new net/http
routing to oapi-codegen so folks could use the new lightweight functionality built into the standard library.
I ended up getting rather frustrated, though, as I thought I'd configured it all correctly, but ended up receiving HTTP 404s.
The code looked like this:
package main
import (
"log"
"net/http"
)
func main() {
mux := http.NewServeMux()
mux.HandleFunc("GET /", func(w http.ResponseWriter, r *http.Request) {})
mux.HandleFunc("GET /pets/{id}", func(w http.ResponseWriter, r *http.Request) {
log.Printf("Called pet %s", r.PathValue("id"))
})
s := &http.Server{
Handler: mux,
Addr: ":8080",
}
log.Fatal(s.ListenAndServe())
}
And I was running Go 1.22, but still couldn't get the new behaviour π€ Instead I was receiving HTTP 404s:
$ curl http://localhost:8080/pets/5 -i
HTTP/1.1 404 Not Found
Content-Type: text/plain; charset=utf-8
X-Content-Type-Options: nosniff
Date: Mon, 04 Mar 2024 13:41:32 GMT
Content-Length: 19
404 page not found
Thanks to Devin C on the Gopher Slack, who helped point out that it was due to my go.mod
not being updated to also note that I'm on Go 1.22:
module ...
-go 1.20
+go 1.22
Once this change has been made, I can then see the correct behaviour.
As I've just hit this same issue, again, I've decided to write this up as a form of blogumentation to save me in the future, and I'm sure hopefully some others bumping into the same thing.