📚Cheatsheets

Cheatsheet collection for go, rust, python, shell and javascript.

Print all routes in Gorilla Mux Router

Collect all gorilla mux routes and print to stdout.

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

	"github.com/gorilla/mux"
)

func PrintRoute(router *mux.Router) {
	router.Walk(func(route *mux.Route, router *mux.Router, ancestors []*mux.Route) error {
		t, err := route.GetPathTemplate()
		if err != nil {
			log.Println(err)
			return err
		}
		fmt.Println(strings.Repeat("| ", len(ancestors)), t)
		return nil
	})
}

Usage :

func handler(w http.ResponseWriter, r *http.Request) {
	return
}

func main() {
	r := mux.NewRouter()
	r.HandleFunc("/", handler)
	r.HandleFunc("/products", handler)
	r.HandleFunc("/articles", handler)
	r.HandleFunc("/blog", handler)
	r.HandleFunc("/blog/post", handler)
	r.HandleFunc("/blog/post/{slug}", handler)
	r.HandleFunc("/articles/{id}", handler)
	PrintRoute(r)
}