Issues with new routing feature from Go 1.22

Golang version 1.22.0 introduces Rest style routing with the http router. It is supposed to support routing enhancements according to this blog article: Routing Enhancements for Go 1.22 - The Go Programming Language

For example

http.Handle(“GET /posts/{id}”, handlePost2)

would allow you to do

idString := req.PathValue(“id”)

I am using the following Golang program:

package main

import (
	"fmt"
	"log"
	"net/http"
)

func main() {
	http.HandleFunc("GET /articles/{id}", articles)

	log.Fatalln(http.ListenAndServe(":8080", nil))
}

func articles(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintln(w, "hello")
}

However, when I use this curl command

curl -X GET localhost:8080/articles/11

I get a 404 page not found

I am using the latest go version:

go version
go version go1.22.0 linux/amd64

I am running the program with “go run”

I expected my handler to handle this according to this routing. Why is that?

check your go.mod version when upgrading to Go 1.22

1 Like

Hi,

I tries this Go Playground - The Go Programming Language and it works.
Are you sure you’re using Go v1.22 ?

Thank you! That fixed it.

I was sure I was using the right version as I was able to use r.PathValue(). Maybe PathValue was introduced in an earlier version?

If anyone ever has this issue, you can run this from the terminal to update it:

go mod edit -go=1.22

Thanks! That’s what it was, I needed to update my go mod file. Lesson learned for next time, running “go version” isn’t enough, the mod file has to be updated too.