DEV Community

Cover image for Print all routes in Chi router
Gurleen Sethi
Gurleen Sethi

Posted on

Print all routes in Chi router

👉 Read the complete 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 main

import (
    "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"))
}
Enter fullscreen mode Exit fullscreen mode

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 the complete article on TheDeveloperCafe

👉 Read the complete article on TheDeveloperCafe 👈

Top comments (0)