Print all routes in Chi router

Gurleen Sethi
TheDeveloperCafe
Published in
2 min readAug 15, 2022

👉 Read the full article on TheDeveloperCafe 👈

Getting Started

If you have been writing Go you probably have heard of the popular http router chi. In this article you are going to learn how to print all the routes registered in a router, this is very helpful for debugging purposes.

If you want to learn about chi, please read Restful routing with Chi.

Setting up a router

I assume you have a project with chi setup (if not please install chi).

Let’s assume an application that has a router with 3 routes registered.

package mainimport (
"fmt"
"github.com/go-chi/chi/v5"
"net/http"
)
func main() {
router := chi.NewRouter()
router.Get("/articles", sayHello)
router.Get("/articles/{articleID}", sayHello)
router.With(func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
next.ServeHTTP(w, r)
})
}).Post("/articles", sayHello) // 👈 route with middleware
}
func sayHello(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello World"))
}

Look closely one of these routes (POST route) has a middleware setup as well. So now we want to print out all the routes and the number of middlewares setup on each routes.

Print routes with chi.Walk #

We want to print each route in the format: [<method>]: '<route>' has <x> middlewares.

…read complete article on TheDeveloperCafe blog

👉 Read the full article on TheDeveloperCafe 👈

--

--