英文:
Reversing a Subrouter in Gorilla / Mux
问题
我想获取一个命名子路由的路径,但是下面的代码不起作用。当我尝试在非子路由上使用相同的逻辑时,它可以正常工作。我该如何获取命名子路由的路径?
router = mux.NewRouter() // 这是一个全局变量
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)
谢谢!
英文:
I would like to get the path for a named subroute but my code below does not work. When I try to use the same logic on a non-subroute, it works fine. How do I get the path of a named subroute?
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)
The above gives this error:
panic: mux: route doesn't have a host or path
Now if I do router.HandleFunc("/home", c.GetHomeHandler).Name("home")
, it works just fine.
Appreciate your help.
Update:
This is a reasonable workaround but it avoids creating a Subroute. It is fine for the example I had above but probably not ideal as you will not get all the benefits of a Subroute.
router.Path("/home").Methods("GET").HandlerFunc(c.GetHomeHandler).Name("home")
router.Path("/home").Methods("POST").HandlerFunc(c.PostHomeHandler)
Thanks!
答案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)
英文:
I believe you'd need to specify your subroute with a PathPrefix, then in order to support /home and /home/ enable 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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论