go - 具有独立处理程序的 PathPrefixed 子路由器

标签 go mux gorilla

鉴于以下 ( 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/

相关文章:

go - 使用 Go olivere/elastic 进行 Elasticsearch 查询以过滤 value1 == value2 的文档

unit-testing - 在golang中重新定义const进行测试

go - 使用http Mux请求正文验证

http - 第二个FileServer提供html但不提供图像

go - 如何检查 URL 参数是否存在

go - 嵌入式类型的类型断言

string - 将特定字符替换为给定单词中的适当字符

json - 我无法使用从请求中获取的数据创建结构

go - 在 HTTP 处理程序中提供子目录服务 [GoLang]

go - 为什么http.HandlerFunc总是返回相同的随机数