在机架应用程序中,如何判断哪个Web服务器作为Rack Handler运行?
例如,在config.ru中,我想打开我是否正在运行WEBrick:
unless running_webrick?
redirect_stdout_and_stderr_to_file
end
run App
def running_webrick?
???
end
答案 0 :(得分:0)
传递给堆栈中每个组件的环境哈希都有一个SERVER_SOFTWARE
密钥。运行此命令并观察网页上的输出:
require 'rack'
class EnvPrinter
def call env
[200, {'content-type' => 'text/plain'}, [env.inspect]]
end
end
run EnvPrinter.new
如果使用rackup执行,webrick将用作服务器(这是默认设置),SERVER_SOFTWARE
将类似于WEBrick/1.3.1 (Ruby/1.9.3/2013-01-15)
。如果使用独角兽,它将类似于Unicorn 4.5.0
。此机架代码根据运行的服务器返回自定义响应:
require 'rack'
class EnvPrinter
def call env
response = case env.fetch('SERVER_SOFTWARE')
when /webrick/i then 'Running on webrick'
when /unicorn/i then 'Running on unicorn'
when /thin/i then 'Running on thin'
else "I don't recognize this server"
end
[200, {'content-type' => 'text/plain'}, [response]]
end
end
run EnvPrinter.new