【发布时间】:2014-03-09 05:27:30
【问题描述】:
我正在尝试了解 Rack 的工作原理,并且正在测试来自 this rack tutorial 的示例。
该示例创建了一个“hello world”机架应用程序,以及两个微不足道的中间件,然后将它们全部运行:
带有中间件的示例机架应用
这是工作代码,您可以将其保存到名为 app.rb 的文件中,然后在命令行中使用 ruby app.rb 在本地运行它:
require 'rack'
require 'rack/server'
class EnsureJsonResponse
def initialize(app)
@app = app
end
# Set the 'Accept' header to 'application/json' no matter what.
# Hopefully the next middleware respects the accept header :)
def call(env)
puts "JSON"
env['HTTP_ACCEPT'] = 'application/json'
@app.call env
end
end
class Timer
def initialize(app)
@app = app
end
def call(env)
puts "Timer"
before = Time.now
status, headers, body = @app.call env
headers['X-Timing'] = (Time.now - before).to_s
[status, headers, body]
end
end
class HelloWorldApp
def self.call(env)
puts "HelloWorld"
[200, {}, ["hello world"]]
end
end
app = Rack::Builder.new do
use Timer # put the timer at the top so it captures everything below it
use EnsureJsonResponse
run HelloWorldApp
end
Rack::Server.start :app => app
输出
如果您向网页发出单个请求,您会看到以下内容:
+>ruby app.rb
>> Thin web server (v1.4.1 codename Chromeo)
>> Maximum connections set to 1024
>> Listening on 0.0.0.0:8080, CTRL+C to stop
Timer
JSON
HelloWorld
Timer
JSON
HelloWorld
为什么每个中间件以及底层应用都会在一个请求中被调用两次?
【问题讨论】: