【发布时间】:2015-01-28 12:36:17
【问题描述】:
我想获取命名子路由的路径,但下面的代码不起作用。当我尝试在非子路由上使用相同的逻辑时,它工作正常。如何获取命名子路由的路径?
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)
谢谢!
【问题讨论】: