From 8f58e460f575b719a334fe704a93ae2fcf17627d Mon Sep 17 00:00:00 2001 From: xiaoshuai Date: Sat, 12 Dec 2020 00:36:09 +0800 Subject: [PATCH] Add Mount method to Route. With Mount method, we can simplify subrouter with tidy code. ``` todos := r.PathPrefix("/todos").Subrouter() todosResource{}.SubrouterFunc(todos) ``` ``` r.Mount("/todos", todosResource{}.SubrouterFunc) ``` ``` type todosResource struct{} func (rs todosResource) SubrouterFunc(r *mux.Router) { r.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { _, _ = fmt.Fprintln(w, "entry [/todos/].") }) r.HandleFunc("/list", func(w http.ResponseWriter, r *http.Request) { _, _ = fmt.Fprintln(w, "entry [/todos/list].") }) } ``` --- route.go | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/route.go b/route.go index 750afe5..5e28f9f 100644 --- a/route.go +++ b/route.go @@ -488,6 +488,12 @@ func (r *Route) Subrouter() *Router { return router } +// Mount registers a subrouter for the route. +func (r *Router) Mount(prefix string, wrapFunc func(r *Router)) { + sub := r.PathPrefix(prefix).Subrouter() + wrapFunc(sub) +} + // ---------------------------------------------------------------------------- // URL building // ----------------------------------------------------------------------------