在 Gorilla / Mux 中逆向子路由器

Reversing a Subrouter in Gorilla / Mux

我想获取命名子路径的路径,但我下面的代码不起作用。当我尝试在非子路径上使用相同的逻辑时,它工作正常。如何获取命名子路径的路径?

router = mux.NewRouter() // this is a global variable
home := router.Path("/home").Subrouter()
home.Methods("GET").HandlerFunc(c.GetHomeHandler).Name("home")
home.Methods("POST").HandlerFunc(c.PostHomeHandler)

p, err := router.Get("home").URL()
if (err != nil) { panic (err) }
log.Printf(p.Path)

上面给出了这个错误:

panic: mux: route doesn't have a host or path

现在,如果我这样做 router.HandleFunc("/home", c.GetHomeHandler).Name("home"),它工作得很好。

感谢您的帮助。

更新:

这是一个合理的解决方法,但它避免了创建子路径。这对于我上面的示例来说很好,但可能并不理想,因为您不会获得子路径的所有好处。

router.Path("/home").Methods("GET").HandlerFunc(c.GetHomeHandler).Name("home")
router.Path("/home").Methods("POST").HandlerFunc(c.PostHomeHandler)

谢谢!

我认为您需要使用 PathPrefix 指定子路径,然后才能支持 /home 和 /home/ 启用 StrictSlash (due to this issue)

router := mux.NewRouter() 
home := router.PathPrefix("/home").Subrouter().StrictSlash(true)
home.Path("/").Methods("GET").HandlerFunc(GetHomeHandler).Name("home")
home.Path("/post/").Methods("POST").HandlerFunc(PostHomeHandler).Name("home-post")


p, err := router.Get("home").URL()
if (err != nil) { panic (err) }
log.Printf(p.Path)

p, err = home.Get("home-post").URL()
if (err != nil) { panic (err) }
log.Printf(p.Path)