Why is Go 1.22's enhanced routing not working for me?

Featured image for sharing metadata for article

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.

Written by Jamie Tanna's profile image Jamie Tanna on , and last updated on .

Content for this article is shared under the terms of the Creative Commons Attribution Non Commercial Share Alike 4.0 International, and code is shared under the Apache License 2.0.

#blogumentation #go.

This post was filed under articles.

Interactions with this post

Interactions with this post

Below you can find the interactions that this page has had using WebMention.

Have you written a response to this post? Let me know the URL:

Do you not have a website set up with WebMention capabilities? You can use Comment Parade.