@elibinary
2016-12-18T05:34:39.000000Z
字数 1343
阅读 809
Rails
Rack provides a minimal interface between webservers that support Ruby and Ruby frameworks.
To use Rack, provide an "app": an object that responds to the call method, taking the environment hash as a parameter, and returning an Array with three elements:
- The HTTP response code
- A Hash of headers
- The response body, which must respond to each
以上描述来自 rack doc
不看不知道,一看吓一跳,rack 的包容之大,应用之广出乎我的想象。
看 rack doc
对 WEBrick, Mongrel, FCGI, Thin, Puma等等还有很多的 web server 都进行了支持,rack-base 的框架也是多的不行。
These frameworks include Rack adapters in their distributions:
Camping
Coset
Espresso
Halcyon
Mack
Maveric
Merb
Racktools::SimpleApplication
Ramaze
Rails
Rum
Sinatra
Sin
Vintage
Waves
Wee
… and many others.
'Any valid Rack app will run the same on all these handlers, without changing anything.' -- doc
Rack provides a minimal, modular and adaptable interface for developing web applications in Ruby.
rack 对 HTTP 请求和响应进行了封装,并对上层提供了一套统一的接口。它需要一个能够响应(response)call 方法的对象,该call方法接收一个 hash 类型的参数 env,并且返回一个三元素的数组
[code, headers, body]
一个简单的例子:
require "rack"
require "awesome_print"
class HelloWorld
def call(env)
ap env
[200, {'tp' => 'tp'}, ['hello world~']]
end
end
Rack::Handler::WEBrick.run HelloWorld.new, Port: 3333
很简单吧
根据文档说明 app 只要是一个拥有一个可以接收 env 参数并返回三元素数组的 call 方法的对象就可以,那么就有了更简单的写法。
app = Proc.new do |env|
['200', {'Content-Type' => 'text/html'}, ['hello world~']]
end
Rack::Handler::WEBrick.run app, Port: 3333