[关闭]
@elibinary 2016-12-18T05:34:39.000000Z 字数 1343 阅读 809

了解 Rack (上)

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 的框架也是多的不行。

  1. These frameworks include Rack adapters in their distributions:
  2. Camping
  3. Coset
  4. Espresso
  5. Halcyon
  6. Mack
  7. Maveric
  8. Merb
  9. Racktools::SimpleApplication
  10. Ramaze
  11. Rails
  12. Rum
  13. Sinatra
  14. Sin
  15. Vintage
  16. Waves
  17. Wee
  18. and many others.

'Any valid Rack app will run the same on all these handlers, without changing anything.' -- doc

Rack 是什么

Rack provides a minimal, modular and adaptable interface for developing web applications in Ruby.

rack 对 HTTP 请求和响应进行了封装,并对上层提供了一套统一的接口。它需要一个能够响应(response)call 方法的对象,该call方法接收一个 hash 类型的参数 env,并且返回一个三元素的数组
[code, headers, body]

一个简单的例子:

  1. require "rack"
  2. require "awesome_print"
  3. class HelloWorld
  4. def call(env)
  5. ap env
  6. [200, {'tp' => 'tp'}, ['hello world~']]
  7. end
  8. end
  9. Rack::Handler::WEBrick.run HelloWorld.new, Port: 3333

很简单吧

根据文档说明 app 只要是一个拥有一个可以接收 env 参数并返回三元素数组的 call 方法的对象就可以,那么就有了更简单的写法。

  1. app = Proc.new do |env|
  2. ['200', {'Content-Type' => 'text/html'}, ['hello world~']]
  3. end
  4. Rack::Handler::WEBrick.run app, Port: 3333

Middleware(TODO)

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注