新手问题 Rack 在整个 Ruby Web 系统中处于什么位置?

caiqinghua · June 17, 2015 · Last by douxiance replied at August 28, 2015 · 4783 hits

RACK 具体作用是什么,在整个 ruby web 系统中 rack 处于什么位置?rails 是怎么使用 rack 的?

一、RACK 基本信息

RACK 官网 http://rack.github.io/ RACK spec http://www.rubydoc.info/github/rack/rack/master/file/SPEC Rack: a Ruby Webserver Interface Rack powers web applications 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 You can handle an app directly:

二、RACK 具体作用是什么?

三、在非 ruby 技术,和 RACK 类似功能的是哪些东东?php java 用什么取代 rack?

四、有没有介绍 web 各种技术的体系结构资料推荐?

Rack 只是一个中间件架构的实现,Rails 本身就是基于 Rack + 其他很多中间件组成的,不信?你在 Rails 项目根目录下执行 rake middleware,就可以看到你的项目当前的中间件列表及其顺序了:

use Rack::Sendfile
use ActionDispatch::Static
use Rack::Lock
use #<ActiveSupport::Cache::Strategy::LocalCache::Middleware:0x00000105bb4328>
use ActiveRecord::Migration::CheckPending
# ... others
use Rack::ConditionalGet
use Rack::ETag
use Warden::Manager
use Bullet::Rack
run ProjectName::Application.routes

关于 Rack 的介绍,网上其实非常多资料: https://www.amberbit.com/blog/2011/07/13/introduction-to-rack-middleware/ https://vimeo.com/user12143456/review/69109140/c72efbd052 http://guides.rubyonrails.org/rails_on_rack.html

还有一个非常棒的视频叫做《Rebuilding a Ruby web server》,可以了解 Ruby 基于 Rack 的 Application Server 的架构。

java 的 j2ee 架构下,可以使用 filter 来做 rack 类似的工作。

Servlet

我的理解:作为“Ruby Webserver Interface”来讲,Rack 是 Web 应用服务器和 Web 应用之间的一个协议,等价物应该是 CGI/Java Servlet 规范/WSGI

Servlet

Ruby 服务器的接口协议 + 网络开发的一些常用工具库 + 服务器端网络中间件框架

A Simple HTTP Server :


[1] pry(main)> require 'rack'
=> true
[2] pry(main)> Rack::Server.start(app: Rack::Directory.new(''), Port: 9292, server: "webrick")
[2015-06-19 10:12:06] INFO  WEBrick 1.3.1
[2015-06-19 10:12:06] INFO  ruby 2.2.0 (2014-12-25) [x86_64-darwin14]
[2015-06-19 10:12:06] INFO  WEBrick::HTTPServer#start: pid=12041 port=9292
localhost - - [19/Jun/2015:10:12:16 CST] "GET /Downloads/ HTTP/1.1" 200 59390
http://127.0.0.1:9292/ -> /Downloads/

#6 楼 @espercn 谢谢,高手讲解,很清楚

#6 楼 @espercn

your lambda has been written wrongly.


[4] pry(main)> Rack::Server.start(app: lambda { |env| [200, {}, ["Hello, World :) "]] }, Port: 9292, server: "webrick")
[2015-06-19 23:52:01] INFO  WEBrick 1.3.1
[2015-06-19 23:52:01] INFO  ruby 2.2.0 (2014-12-25) [x86_64-darwin14]
[2015-06-19 23:52:01] INFO  WEBrick::HTTPServer#start: pid=39622 port=9292

localhost - - [19/Jun/2015:23:52:05 CST] "GET / HTTP/1.1" 200 16
- -> /
localhost - - [19/Jun/2015:23:52:05 CST] "GET /favicon.ico HTTP/1.1" 200 16
- -> /favicon.ico

#12 楼 @jimweirich 谢谢,已修复 :)

一个实现 HTTP 协议的东西。

#8 楼 @suffering 你是最牛的,刨根问底

受益匪浅!

You need to Sign in before reply, if you don't have an account, please Sign up first.