机架URL映射 [英] Rack URL Mapping
问题描述
我正在尝试编写两种Rack路由。机架允许我们这样写这样的路由:
I am trying to write two kind of Rack routes. Rack allow us to write such routes like so:
app = Rack::URLMap.new('/test' => SimpleAdapter.new,
'/files' => Rack::File.new('.'))
对于我来说,我想处理以下路线:
In my case, I would like to handle those routes:
- /或 index
- / *以匹配任何其他路线
所以我尝试了以下方法:
So I had trying this:
app = Rack::URLMap.new('/index' => SimpleAdapter.new,
'/' => Rack::File.new('./public'))
这很好,但是...我不知道如何添加 /路径(作为 / index路径的替代方式)。根据我的测试,路径 / *不解释为通配符。
This works well, but... I don't know how to add '/' path (as alternative of '/index' path). The path '/*' is not interpreted as a wildcard, according to my tests. Do you know how I could do?
谢谢
推荐答案
您是正确的,因为 Rack :: URLMap
不会将路径中的'*'
视为通配符。从路径到正则表达式的实际翻译看起来像这样:
You are correct that Rack::URLMap
doesn't treat '*'
in a path as a wildcard. The actual translation from path to regular expression looks like this:
Regexp.new("^#{Regexp.quote(location).gsub('/', '/+')}(.*)", nil, 'n')
也就是说,它将路径中的任何字符视为文字,但还会匹配具有任何后缀的路径。我相信您要完成所要完成的唯一方法就是使用中间件而不是端点。在您的 config.ru
中,您可能会有类似的内容:
That is, it treats any characters in the path as literals, but also matches a path with any suffix. I believe the only way for you to accomplish what you're attempting is to use a middleware instead of an endpoint. In your config.ru
you might have something like this:
use SimpleAdapter
run Rack::File
和您的 lib / simple_adapter .rb
可能看起来像这样:
And your lib/simple_adapter.rb
might look something like this:
class SimpleAdapter
SLASH_OR_INDEX = %r{/(?:index)?}
def initialize(app)
@app = app
end
def call(env)
request = Rack::Request.new(env)
if request.path =~ SLASH_OR_INDEX
# return some Rack response triple...
else
# pass the request on down the stack:
@app.call(env)
end
end
end
这篇关于机架URL映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!