Sinatra 中的动词不可知匹配
我们可以写
get '/foo' do
...
end
,
post '/foo' do
...
end
这很好。但是我可以在一个路由中组合多个 HTTP 动词吗?
We can write
get '/foo' do
...
end
and
post '/foo' do
...
end
which is fine. But can I combine multiple HTTP verbs in one route?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这可以通过
多路由
扩展 是 sinatra-contrib 的一部分:但是,请注意,您可以自己简单地完成此操作,而无需扩展 via:
或者更优雅地作为元方法:
您可能还对 关于该功能的讨论。
This is possible via the
multi-route
extension that is part of sinatra-contrib:However, note that you can do this simply yourself without the extension via:
Or more elegantly as a meta-method:
You might also be interested in this discussion on the feature.
FWIW,我只是手动执行此操作,没有辅助方法或扩展:
尽管如果您经常执行此操作,那么将其抽象出来当然是有意义的。
FWIW, I just do it manually, with no helper methods or extensions:
Although if you're doing it a lot it of course makes sense to abstract that out.
Phrogz 有一个很好的答案,但如果 lambda 或包含 sinatra-contrib 不适合您,那么此元方法将达到与 sinatra-contrib 相同的结果,以达到您的目的:
如果您对能够发送有点谨慎任意方法
self
,那么您可以通过在数组中设置允许方法的白名单来保护自己,然后检查该符号在数组中是否存在。Phrogz has a great answer, but if either lambdas or including sinatra-contrib isn't for you, then this meta method will achieve the same result as sinatra-contrib for your purposes:
If you're a little wary of being able to send arbitrary methods to
self
, then you can protect yourself by setting up a whitelist of allowed methods in an array, and then checking for the symbol's presence in the array.这是一个服务不可用的服务器,我设法在单行上获得它:)
我实际上用它来测试一些客户端代码在面对 503 时的行为。
Here's a service-unavailable server that I managed to get on single line :)
I actually used this to test the behavior of some client code in the face of 503s.