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

标签 ruby indexing webserver config rack

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

基本上我想要一个文件 config.ru 告诉 rack 读取当前目录,这样我就可以访问所有文件,就像一个简单的 apache 服务器一样,还可以读取带有索引的默认根目录.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

所以我不知道如何从这里开始......

我也按照教程示例尝试过此操作,但 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

提前致谢

最佳答案

我认为您缺少 rackup 命令。下面是它的使用方法:

rackup config.ru

这将使用 webrick 在端口 9292 上运行你的 Rack 应用程序。您可以阅读“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
}

关于Ruby Rack - 安装一个默认读取 index.html 的简单 Web 服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3863781/

相关文章:

python - 如何在python创建的BaseHTTPSERVER上执行python脚本?

java - 从 ftp 服务器下载文件

ruby-on-rails - Devise 生成的代码在哪里?

java - 我应该使用 ruby​​ 线程还是完全不使用 ruby​​ 线程?

java - Lucene 4.0 IndexWriter updateDocument for Numeric Term

python - Numpy:从数组中选择所有行和列

ruby-on-rails - 在 Rails 应用程序中本地使用 gem 而不修改 Gemfile

ruby-on-rails - 安装 mini_racer (0.2.0) 时出错

mysql - sphinx会和mysql数据源占用同样的内存空间吗?

javascript - 将 Nodejs 与 Typescript 一起使用