gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 06:31:21 24 4
gpt4 key购买 nike

我正在尝试从本教程中获取一些信息: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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com