Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby Rack - mounting a simple web server that reads index.html as default

I'm trying to get some information from this tutorial: http://m.onkey.org/2008/11/18/ruby-on-rack-2-rack-builder

basically I want to have a file config.ru that tell rack to read the current directory so I can access all the files just like a simple apache server and also read the default root with the index.html file...is there any way to do it?

my current config.ru looks like this:

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

So I don't know how to proceed from here...

I've also tried this following the tutorials example but thin doesn't starts properly.

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

Thanks in advance

like image 932
zanona Avatar asked Oct 05 '10 12:10

zanona


2 Answers

I think that you are missing the the rackup command. Here is how it is used:

rackup config.ru

This is going to run your rack app on port 9292 using webrick. You can read "rackup --help" for more info how you can change these defaults.

About the app that you want to create. Here is how I think it should look like:

# 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
}
like image 148
valo Avatar answered Oct 08 '22 06:10

valo


I ended up on this page looking for a one liner...

If all you want is to serve the current directory for a few one-off tasks, this is all you need:

ruby -run -e httpd . -p 5000

Details on how it works: http://www.benjaminoakes.com/2013/09/13/ruby-simple-http-server-minimalist-rake/

like image 30
Benjamin Oakes Avatar answered Oct 08 '22 05:10

Benjamin Oakes