机架中间件中的机架中间件?
Rack Middleware in Rack Middleware?
我正在尝试构建一个使用机架中间件本身 (RackWired) 的机架中间件 GEM。
我有一个现有的应用程序,其 config.ru 使用 Rack::Builder。在那个块 (Rack::Builder) 中,我想指定我的中间件,当它被调用时使用我自己内部的第三方中间件 (rack-cors) 来做一些事情。我知道很困惑。
问题是 Rack::Builder 的上下文在 config.ru 中,因此我的中间件 (RackWired) 无法访问 "use" 第三方中间件 (rack-cors) ).
我努力的目的是here
有没有办法在中间件中使用中间件?
谢谢
是的,我不完全确定你想做什么。但是你可以这样做
class CorsWired
def initialize(app)
@app = app
end
def call(env)
cors = Rack::Cors.new(@app, {}) do
allow do
origins '*'
resource '*', :headers => :any, :methods => [:get, :post, :put, :options, :delete], :credentials => false
end
end
cors.call(env)
end
end
不过你的 config.ru 应该有 use CorsWired
,而不是 use CorsWired.new
我想这就是您要问的问题,但我认为您忽略了中间件的要点。您应该根据自己的需要更改 config.ru
以使用 rack-cors before/after 您的中间件。
require 'rack'
require 'rack/cors'
require './cors_wired'
app = Rack::Builder.new do
use Rack::Cors do
allow do
origins '*'
resource '*', :headers => :any, :methods => [:get, :post, :put, :options, :delete], :credentials => false
end
end
use CorsWired
run lambda { |env| [200, {'Content-Type' => 'text/plain'}, ['OK']] }
end
run app
我正在尝试构建一个使用机架中间件本身 (RackWired) 的机架中间件 GEM。
我有一个现有的应用程序,其 config.ru 使用 Rack::Builder。在那个块 (Rack::Builder) 中,我想指定我的中间件,当它被调用时使用我自己内部的第三方中间件 (rack-cors) 来做一些事情。我知道很困惑。
问题是 Rack::Builder 的上下文在 config.ru 中,因此我的中间件 (RackWired) 无法访问 "use" 第三方中间件 (rack-cors) ).
我努力的目的是here
有没有办法在中间件中使用中间件?
谢谢
是的,我不完全确定你想做什么。但是你可以这样做
class CorsWired
def initialize(app)
@app = app
end
def call(env)
cors = Rack::Cors.new(@app, {}) do
allow do
origins '*'
resource '*', :headers => :any, :methods => [:get, :post, :put, :options, :delete], :credentials => false
end
end
cors.call(env)
end
end
不过你的 config.ru 应该有 use CorsWired
,而不是 use CorsWired.new
我想这就是您要问的问题,但我认为您忽略了中间件的要点。您应该根据自己的需要更改 config.ru
以使用 rack-cors before/after 您的中间件。
require 'rack'
require 'rack/cors'
require './cors_wired'
app = Rack::Builder.new do
use Rack::Cors do
allow do
origins '*'
resource '*', :headers => :any, :methods => [:get, :post, :put, :options, :delete], :credentials => false
end
end
use CorsWired
run lambda { |env| [200, {'Content-Type' => 'text/plain'}, ['OK']] }
end
run app