Rack学习笔记一,一个简单的hello world

来源:互联网 发布:php轻量级论坛 编辑:程序博客网 时间:2024/05/22 17:34

Rack作为Ruby web服务的中间介,在整个开发中是非常重要的。很多框架的基础服务都是基于Rack的。本文做一个简单的hello world。


1, 基本介绍

很简单,Rack只需要一个简单的ruby类,方法,Proc, lamba 等,只要能调用 call方法的代码片段都行
基本的模式

def call(env)[status, [headers], body]end

如下是一个简单的hello_world.rb文件
require 'rubygems'require 'rack'class HelloWorld  def call(env)    [200, {"Content-Type" => "text/html"}, "hello, world"]  end endRack::Handler::Thin.run HelloWorld.new, :Port => 9292

运行 ruby hello_world.rb即可访问

2, 还可以使用Proc 或者 其他的
所以,如下方法都是可行的
Rack::Handler::Thin.run proc {|env| [200, {"Content-Type" => "text/html"}, "Hello Rack!"]}, :Port => 9292

def application(env)  [200, {"Content-Type" => "text/html"}, "Hello Rack!"]endRack::Handler::Thin.run method(:application), :Port => 9292

3, 使用rackup 启动
config.ru
run Proc.new { |env| [200, {"Content-Type" => "text/html"}, ["hello world!"]]  }

然后以  rackup config.ru启动, rackup默认是9292启动的

注意,此处有一个问题, body不能是字符串,因为在1.9.2中,String 没有each 方法了,所以,需要使用数组


原创粉丝点击