如何仅将Rack中间件用于某些路径? [英] How do I use a Rack middleware only for certain paths?

查看:81
本文介绍了如何仅将Rack中间件用于某些路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的Rack应用程序中运行MyMiddleware,但仅适用于某些路径.我希望使用Rack::Builder或至少使用Rack::URLMap,但我不太清楚如何使用.

I'd like to have MyMiddleware run in my Rack app, but only for certain paths. I was hoping to use Rack::Builder or at least Rack::URLMap, but I can't quite figure out how.

这是我认为可行的方法,但无效:

This is what I thought would work, but doesn't:

# in my rackup file or Rails environment.rb:
map '/foo' do
  use MyMiddleware, { :some => 'options' }
end

或者,更好的是,使用Regexp:

Or, better yet, with a Regexp:

map /^foo/ do
  use MyMiddleware, { :some => 'options' }
end

但是map似乎最后要求一个应用程序;它不会仅仅依赖于将控制权交还给其父代. (当机架尝试将那个do...end块的末尾变成一个app时,实际错误是"undefined method 'each' for nil:NilClass".)

But map seems to demand an app at the end; it won't fall back on just passing control back to its parent. (The actual error is "undefined method 'each' for nil:NilClass" from when Rack tries to turn the end of that do...end block into an app.)

是否存在中间件,该中间件需要一系列中间件和一条路径,并且仅在路径匹配时才运行它们?

Is there a middleware out there that takes an array of middlewares and a path and only runs them if the path matches?

推荐答案

您可以让MyMiddleware检查路径,并且在匹配时不将控制权传递给下一个中间件.

You could have MyMiddleware check the path and not pass control to the next piece of middle ware if it matches.

class MyMiddleware
  def initialize app
    @app = app
  end
  def call env
    middlewary_stuff if env['PATH_INFO'] == '/foo'
    @app.call env
  end

  def middlewary_stuff
    #...
  end
end

或者,您可以不使用dslness使用URLMap.看起来像这样:

Or, you could use URLMap w/o the dslness. It would look something like this:

main_app = MainApp.new
Rack::URLMap.new '/'=>main_app, /^(foo|bar)/ => MyMiddleWare.new(main_app)

URLMap实际上是非常简单.

URLMap is actually pretty simple to grok.

这篇关于如何仅将Rack中间件用于某些路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆