Skip to content

Instantly share code, notes, and snippets.

@wulftone
Last active December 16, 2015 04:19
Show Gist options
  • Save wulftone/5376425 to your computer and use it in GitHub Desktop.
Save wulftone/5376425 to your computer and use it in GitHub Desktop.
Silly little webserver
# If you have ruby installed, you can use this file to run a basic web server
# and avoid silly cross-site forgery issues when doing your assignments.
#
# * Install ruby, if you haven't already
# Macs come with ruby, so just open up a terminal and type: ruby -v
# and press Return (or Enter or whatever). If you get a response,
# you have ruby already! Move to the next step. If not, consult Google.
#
# Windows users can easily install ruby, just check out http://rubyinstaller.org/
# When you're done installing, open up a command prompt (or powershell) and
# type: ruby -v
# and press Enter. If you get a response, you have ruby! Move to the next step.
#
# * From the command line (powershell, or cmd, or terminal), run:
# gem install rack --no-rdoc --no-ri
#
# * Put this file in the same place as your `.html` file you want to play with.
#
# * From the command line, run the following command:
# rackup config.ru
#
# Then you should have a running webserver.
#
# Now, open your browser at:
# http://localhost:9292
#
# You should see a list of files from the directory where you started the webserver.
# If you haven't put your assignment into this directory yet, do so now, and refresh
# the page. Now click on the file and you should see your assignment in all of its
# assigned glory.
#
# Enjoy!
# Here, we set `@root` to the directory this file resides in.
@root = File.expand_path(File.dirname(__FILE__))
# `run` is a Rack command, so when you run `rackup` from the command line,
# it looks for this `run` and starts up your web server.
run Proc.new { |env|
# Extract the requested path from the request
path = Rack::Utils.unescape(env['PATH_INFO'])
index_file = @root + "/index.html"
if File.exists?(index_file)
if RUBY_VERSION < "1.9"
[200, {'Content-Type' => 'text/html'}, File.read(index_file)]
else
[200, {'Content-Type' => 'text/html'}, [File.read(index_file)]]
end
else
puts 'Index file does not exist, displaying directory tree.'
Rack::Directory.new(@root).call(env)
end
}
@wulftone
Copy link
Author

To save this file, click on the little <> in the top-right corner of the file's box and save that page where your assignment files will be. You can always move the file later if you "miss" the right directory. : )

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment