鉴于以下 ( complete example at Go playground ):
// Collection
root := r.PathPrefix("/widgets/").Subrouter()
root.Methods("POST").Handler(h.Create)
// Individual
object := root.PathPrefix("/{uuid}").Subrouter()
// ~neither: object := root.PathPrefix("/{uuid}").Subrouter()
object.Methods("GET").Handler(h.Show)
object.Methods("PUT").Handler(h.Replace)
object.Methods("DELETE").Handler(h.Delete)
// Relationships
object.Methods("GET").Path("/foos").Handler(eh.Foos)
object.Methods("GET").Path("/bars").Handler(eh.Bars)
我原以为以下 URL 会触发相应的处理程序,但我似乎无法让它工作:
✔ POST /widgets => h.Create
✔ GET /widgets/123 => h.Show (assumes PathPrefix('/{uuid}'))
✔ GET /widgets/123/ => h.Show (required if 'PathPrefix('/{uuid}/')')
✖ GET /widgets/123/foos => h.Foos (actually routes h.Show)
✖ GET /widgets/123/bars => h.Bars (actually routes h.Show)
不幸的是,最后两个显然都不是可路由的,它们都触发了 h.Show
,谁能指出我做错了什么?我可能期望有一个无限制的 {uuid}
(没有尾部斜杠)可以继续运行,忽略 /
但事实似乎并非如此.
我什至不知道这是否与 Github 上仍然开放的 Subrouter strict-slash 问题有关 (#31),但据我所知,我确实尝试了那里的替代方案。 (即 object.Methods("GET").Path("/").Handler(h.Show)
)
Handler 是否可以通过 Methods()
挂载到 object
根上以阻止任何进一步的路由匹配?
最佳答案
问题是 gorilla/mux
触发了第一个匹配的处理程序。 第一个匹配的处理程序很重要。
这意味着永远不会找到逻辑上在 /{id}/
下的路由,因为与它们匹配的路由首先由父处理程序匹配。
将代码更改为以下使其按预期工作:
// Collection
root := r.PathPrefix("/widgets/").Subrouter()
object := root.PathPrefix("/{uuid}").Subrouter()
// Relationships
object.Methods("GET").Path("/foos").Handler(eh.Foos)
object.Methods("GET").Path("/bars").Handler(eh.Bars)
// Individual
root.Methods("POST").Handler(h.Create)
object.Methods("GET").Handler(h.Show)
object.Methods("PUT").Handler(h.Replace)
object.Methods("DELETE").Handler(h.Delete)
然后一切就完美了。
关于go - 具有独立处理程序的 PathPrefixed 子路由器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28826101/