2

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

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)

谢谢!

4

1 回答 1

3

我相信您需要使用 PathPrefix 指定您的子路由,然后才能支持 /home 和 /home/ 启用 StrictSlash (由于这个问题

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)
于 2015-01-24T04:48:08.790 回答