Ruby Rack - 安装一个简单的Web服务器,默认读取index.html

zan*_*ona 19 ruby indexing webserver rack config

我正在尝试从本教程中获取一些信息:http://m.onkey.org/2008/11/18/ruby-on-rack-2-rack-builder

基本上我想要一个config.ru告诉机架读取当前目录的文件,这样我就可以像一个简单的apache服务器一样访问所有文件,并且还可以使用index.html文件读取默认的根...有什么方法可以做到这一点?

我目前config.ru看起来像这样:

run Rack::Directory.new('')
#this would read the directory but it doesn't set the root to index.html


map '/' do
  file = File.read('index.html')
  run Proc.new {|env| [200, {'Content-Type' => 'text/html'}, file] }
end
#using this reads the index.html mapped as the root but ignores the other files in the directory
Run Code Online (Sandbox Code Playgroud)

所以我不知道怎么从这里开始......

我也按照教程示例尝试了这个但是thin没有正确启动.

builder = Rack::Builder.new do

  run Rack::Directory.new('')

  map '/' do
    file = File.read('index.html')
    run Proc.new {|env| [200, {'Content-Type' => 'text/html'}, file] }
  end

end

Rack::Handler::Thin.run builder, :port => 3000
Run Code Online (Sandbox Code Playgroud)

提前致谢

val*_*alo 37

我认为你错过了rackup命令.以下是它的使用方法:

rackup config.ru
Run Code Online (Sandbox Code Playgroud)

这将使用webrick在端口9292上运行您的机架应用程序.您可以阅读"rackup --help"以获取有关如何更改这些默认值的更多信息.

关于您要创建的应用程序.以下是我认为它应该是这样的:

# This is the root of our app
@root = File.expand_path(File.dirname(__FILE__))

run Proc.new { |env|
  # Extract the requested path from the request
  path = Rack::Utils.unescape(env['PATH_INFO'])
  index_file = @root + "#{path}/index.html"

  if File.exists?(index_file)
    # Return the index
    [200, {'Content-Type' => 'text/html'}, File.read(index_file)]
    # NOTE: using Ruby >= 1.9, third argument needs to respond to :each
    # [200, {'Content-Type' => 'text/html'}, [File.read(index_file)]]
  else
    # Pass the request to the directory app
    Rack::Directory.new(@root).call(env)
  end
}
Run Code Online (Sandbox Code Playgroud)

  • 警告:不要在生产应用程序中使用它!您可以简单地读取整个服务器上的任何文件,因为代码不会检查生成的文件是否包含在@root中.只需做GET /../../../../etc/passwd就可以获得/ etc/passwd(好吧,你必须尝试".."条目的数量) (8认同)
  • 机架规格要求机身响应为阵列.这就像魅力一样确保:`[File.read(index_file)]`作为响应的第三个元素. (4认同)

Ben*_*kes 10

我最后在这个页面上寻找一个班轮......

如果您只想为当前目录提供一些一次性任务,那么这就是您所需要的:

ruby -run -e httpd . -p 5000
Run Code Online (Sandbox Code Playgroud)

有关其工作原理的详细信息:http: //www.benjaminoakes.com/2013/09/13/ruby-simple-http-server-minimalist-rake/


sin*_*inm 8

你可以使用Rack :: Static来做到这一点

map "/foo" do
  use Rack::Static, 
    :urls => [""], :root => File.expand_path('bar'), :index => 'index.html'
  run lambda {|*|}
end
Run Code Online (Sandbox Code Playgroud)